Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGINX: remove part of url permanantly

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

like image 479
Pulkit Sharma Avatar asked Jan 19 '17 10:01

Pulkit Sharma


People also ask

What is rewrite rules in Nginx?

NGINX rewrite rules are used to change entire or a part of the URL requested by a client. The main motive for changing an URL is to inform the clients that the resources they are looking for have changed its location apart from controlling the flow of executing pages in NGINX.

What is return 301 in nginx?

Temporary and Permanent Nginx Redirect Explained To map this change, the redirects response code 301 is used for designating the permanent movement of a page. These kinds of redirects are helpful when the user wants to change the domain name and no longer wants a browser to access it.

What does $Uri mean in nginx?

It is exactly the $uri/ part that makes nginx assuming an URI can be a directory name and looking for an index file presence inside it.


2 Answers

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;
like image 126
Richard Smith Avatar answered Nov 05 '22 18:11

Richard Smith


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;
    }
}
like image 33
Opv Avatar answered Nov 05 '22 18:11

Opv