Dec 24, 2016

f Comment

[SOLVED] How to Let Nginx Rewrite URL & Forward URL Parameters?

Amazon If you use Nginx as your web server, you may be wondering how to rewrite a URL and carry over the URL parameters of the original web request to the rewritten string. For example, let's say a web request hits your Nginx web server at the following location:

http://www.chtoen.com/about-me.php?m=0

And you would like Nginx to rewrite it as follows:

/index.php?path=about-me.php&m=0

You would think this is easy, but without someone to guide you through it, you'd be totally lost. Let me tell you how to make Nginx forward the original request's query string to the rewritten string while rewriting the request.

I am using Nginx 1.4.6

Solution

In my server block, I might have the following
location / {
  if (!-f $request_filename) {
    rewrite ^/(.+)$ /index.php?path=$1&$query_string last;
    break;
  }
}
This means if the request does not match any existing file (by the name of the file), then let Nginx go ahead and rewrite it so that the following request:

http://www.chtoen.com/about-me.php?m=0

becomes

/index.php?path=about-me.php&m=0

$query_string contains all the URL parameters of the original web request. For example, let's say the URL request is:

http://www.chtoen.com/about-me.php?a=1&b=2

Then $query_string would contain the value "a=1&b=2" the URL will be rewritten by Nginx as the following:

/index.php?path=about-me.php&a=1&b=2

This is how you ask Nginx to forward the URL parameters (aka arguments or query string) of the URL request to the rewritten string by Nginx. Questions? Let me know!

Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael