Nitin Nitin - 4 months ago 15
PHP Question

Rewrite rules not working on nginx

I have the following rewrite rules in sites-available/myapp.conf. My setup is Nginx, php5-fpm.

location / {
try_files $uri $uri/ /index.php;

# also tried
# try_files $uri $uri/ /index.php$is_args$args;
# try_files $uri $uri/ /index.php$args;

}
# also tried
# replacing last with break

rewrite "^/([a-zA-Z]+)/?$" "/index.php?lang=$1" last;
rewrite "^/([a-zA-Z]+)/([a-zA-Z0-9]+)/?$" "/index.php?lang=$1&page=$2" last;

location ~ \.php {

try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_nam$
fastcgi_param SCRIPT_NAME $fastcgi_script_name;

#fastcgi_pass unix:/var/run/php5-fpm.sock;

fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
}


I have also tried wrapping the rewrite rules in a @rewrite block but no success.

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


Passing the variables manually does work

index.php?lang=en&page=pageName&type=typeName


Can someone please help solve this. Spend the entire night already but no luck.

Answer

The problem seem to be that fpm processes were still active or the following problem caused the error:

2016/06/03 02:06:24 [emerg] 6604#6604: bind() to 0.0.0.0:80 failed (98: Address already in use)
2016/06/03 02:06:24 [emerg] 6604#6604: still could not bind()

I restarted nginx after each change with success but the rewrite rules would not work. Using

sudo fuser -k 80/tcp

solved the problem. Hope this is useful for someone else.

Where:

fuser - identify processes using files or sockets

-k Kill processes accessing the file.

(src: http://geektechinfo.blogspot.nl/2013/09/starting-nginx-nginx-emerg-bind-to.html)

If fuser does not work, try killing all active nginx processes:

sudo killall -KILL nginx

And (re)start nginx:

sudo service nginx restart