Migrating from Apache to NGINX – config change

John asked:

I am tring to migrate a legacy website from Apache to Nginx, but I can’t rewrite the htaccess file to nginx config.

Current htaccess:

<IfModule mod_rewrite.c>
RewriteEngine on
Options +FollowSymLinks
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*) $1.php?rewrite=$2 [QSA]

I’ve tried this nginx config (already tried a lot of modification but nothing is worked):

    location ~ \.php(/|$) {
    #try_files $uri $uri/ $uri?rewrite=$args; # Not working
    try_files $uri $uri.php $uri?rewrite=index.php; # not working
    #try_files = $document_uri.php?rewrite=$args; #  not working
    fastcgi_pass localhost:8003;

What am I missing?

My answer:

None of those "work" because the regex you specified in your location isn’t the same as the regex you specified in Apache’s .htaccess, and you aren’t trying to use matches from it in try_files.

For the .htaccess you have posted, something like this should be more appropriate:

location ~ ^(.*)/(.*) {
    try_files $uri $1.php?rewrite=$2&$args =404;

This has the following effect: First try a static file, then a matching PHP script, otherwise return a 404.

Note that you don’t fastcgi_pass here, but in another location specifically for handling PHP files.

location ~ \.php$ {
    #...fastcgi config

When possible, you should consider refactoring the app to use a proper front controller. This will also reduce the complexity of your nginx configuration.

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.