Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to learn how to use nginx and how to use its rewrite functionality

Nginx seems to be doing the rewrite:

2012/03/27 16:30:26 [notice] 16216#0: *3 "foo.php" matches "/foo.php", client:, server: localhost, request: "GET /foo.php HTTP/1.1", host: ""
2012/03/27 16:30:26 [notice] 16216#0: *3 rewritten data: "img.php", args: "", client:, server: localhost, request: "GET /foo.php HTTP/1.1", host: ""

but in my access log I am getting the following: - - [27/Mar/2012:16:26:54 +0000] "GET /foo.php HTTP/1.1" 404 31 "-" "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0" - - [27/Mar/2012:16:30:26 +0000] "GET /foo.php HTTP/1.1" 404 31 "-" "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0"

There is an img.php in the root directory so I am not sure why I am getting a 404 error

Here is part of the configuration block:

rewrite foo.php img.php last;

location / {

        try_files $uri $uri/ /index.html;

location ~ \.php$ {
        fastcgi_index index.php;
        include fastcgi_params;

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
location ~ /\.ht {
        deny all;
share|improve this question
up vote 3 down vote accepted

You need to provide a complete path (relative to the document root) as the destination:

rewrite foo.php /img.php last;

Adding the slash before img.php should be sufficient (tested on Nginx 1.0.14/CentOS 6).

Nginx will take the path it generates and, if it starts with http:// will perform a 301 or 302 redirect, and otherwise will append it to the document root. In the latter case, the new path needs to start with a slash.

Additionally, if you only want to match the 'foo.php' in the document root, you should precede that argument with a slash as well (not only is it more specific, but it should be quicker to match):

rewrite ^/foo.php$ /img.php last;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.