8

I am trying to convert a very simple rewrite from a previous nginx version to the current one looking like below:

location / {
   if ( !-f $request_filename ) {
     rewrite ^/([a-z]*)$ /index.php?action=$1;
     rewrite ^/([a-z]*)/(.*)$ /index.php?action=$1&item=$2;
   }
}

This is how far I have gotten. The index page shows up, but any page that should be rewritten like above, instead throws 404's:

server {

    listen 80 default;
    root /var/www;
    index index.php;
    server_name _;

    location / {
        try_files $uri $uri/ /index.php?action=$uri&item=$args;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

What am I doing wrong here?

  • What's happening exactly? Part of the problem is $uri and $args are not properly encoded. – Luke Sep 17 '12 at 17:23
  • 404 is thrown with File not found. if I use either URI /page or /page/id – Industrial Sep 17 '12 at 17:25
  • What happens when you do just try_files $uri $uri/ /index.php? – Luke Sep 17 '12 at 17:27
  • Index.php works nicely, but anything that should be rewritten ends up in 404's – Industrial Sep 17 '12 at 17:29
  • Try try_files $uri $uri/ /index.php?$args. You should be able to get the URL with $_SERVER['REQUEST_URI']. $_GET should work normally. – Luke Sep 17 '12 at 17:32
9

This should work:

location / { 
    try_files $uri $uri/ @rules; 
} 

location @rules { 
    rewrite ^/([a-z]*)$ /index.php?action=$1; 
    rewrite ^/([a-z]*)/(.*)$ /index.php?action=$1&item=$2; 
}

location /index.php { 
    fastcgi_pass 127.0.0.1:9000; 
    include fastcgi_params; 
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
}
| improve this answer | |
  • Hmm. In your first example, index.php will load, but any static files or URI requests such as /page1/item will return the index.php – Industrial Sep 17 '12 at 18:08
  • That's odd. try_files should be taking care of that. – Luke Sep 17 '12 at 18:11
  • Tried the second example as well. Same issue there – Industrial Sep 17 '12 at 18:11
  • I'm assuming try_files $uri $uri/ works with static files? – Luke Sep 17 '12 at 18:16
  • 1
    let us continue this discussion in chat – Luke Sep 17 '12 at 18:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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