11

I have redesigned a website and changed the url formats too. Now i need to change the old url to new one.

Here is my old url:

http://www.example.com/forum/showPost/2556/Urgent-Respose

The new url will be:

http://www.example.com/2556/Urgent-Respose

How to redirect to new url using nginx by removing /forum/showPost from url?

Edited: Also this url:

http://www.tikshare.com/business/showDetails/1/Pulkit-Sharma-and-Associates,-Chartered-Accountants-in-Bangalore

New url:

http://www.tikshare.com/classifieds/1/Pulkit-Sharma-and-Associates,-Chartered-Accountants-in-Bangalore

Above link is complete removing whereas this link is to replace business/showDetails with classifieds

Pulkit Sharma
  • 264
  • 1
  • 2
  • 18
  • Please refer following url, uses same kind of solution : http://serverfault.com/questions/302509/how-to-quick-and-easy-remove-part-of-an-url-in-nginx-with-httprewritemodule – Opv Jan 19 '17 at 10:51
  • @Opv please explain in comment where to put it and only one line will work. New to servers tech. – Pulkit Sharma Jan 19 '17 at 10:54

2 Answers2

10

There are a number of options. You could protect the rewrite within a location block which would be quite efficient as the regular expression is only tested if the URI prefix matches:

location ^~ /forum/showPost {
    rewrite ^/forum/showPost(.*)$ $1 permanent;
}

See this document for more.

You used permanent in your question - which generates a 301 response.

If you use redirect instead of permanent - a 302 response will be generated.

If you use last instead of permanent - an internal redirect will occur and the browser address bar will continue to show the old URL.

In response to your comment:

rewrite ^/forum/showPost(.*)$ /post$1 permanent;
Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • Thank you. It works but is it 301 redirect. Also suppose if my new url contains new word like say http://www.example.com/post/2556/Urgent-Respose. What should be changed? – Pulkit Sharma Jan 19 '17 at 11:07
  • firefox gives 414 error. URI too large. Worked well on safari. – Pulkit Sharma Jan 19 '17 at 11:24
  • Look at your `nginx` access log and Firefox's `Live HTTP Headers` to try to diagnose the problem, The `rewrite` itself is fine - there must be some other interaction going on. Also, clear the Firefox cache, as it can be difficult to diagnose problems in the presence of stale cache data. – Richard Smith Jan 19 '17 at 11:29
  • Thanks a lot. Made my day. – Pulkit Sharma Jan 19 '17 at 11:46
5
server 
{
    listen 80; ## Listen on port 80 ##
    server_name example.com;  ## Domain Name ##
    index index.html index.php;  ## Set the index for site to use ##
    charset utf-8; ## Set the charset ##
    location ^~ /forum/showPost {
        rewrite ^/forum/showPost(.*)$ $1 permanent;
    }
    location ^~ /business/showDetails {     
        rewrite ^(.*)business/showDetails(.*)$ classifieds$1 permanent;
    }
}
Opv
  • 440
  • 1
  • 3
  • 17