Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question
    
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
show 3 more comments

1 Answer

up vote 5 down vote accepted

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; 
}
share|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
show 2 more comments

Your Answer

 
discard

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.