How to convert this very simple .htaccess to nginx?

Sandro Benevides asked:

I’m using this .htaccess that pass everything after url to $param, so
domain.com/news/id goes to php as $_GET[‘param’]=news/id. But nginx is always throwing me to 404 page.

My htaccess:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule  (.*) index.php?param=$1

What I tried in nginx default.conf:

server {
        listen 80;
        listen [::]:80;
    server_name domain.com;
        root    /var/www/html;

        location / {
                if (!-f $uri){
                        set $rule_0 1$rule_0;
                }
                if (!-d $uri){
                        set $rule_0 2$rule_0;
                }
                if ($rule_0 = "21"){
                rewrite ^(.*) index.php?param=$1;
                }
        }
}

My answer:


You don’t use if here at all, nor do you manually check for the existence of files. This common pattern is handled instead by try_files.

For example:

location / {
    try_files $uri $uri/ /index.php?param=$uri;
}

(If your web app is broken and can’t handle the leading / in the URI, fix the web app if possible, or see this question if not.)


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.