Question

Working on switching from apache to nginx and I am new to nginx and still trying to figure out the rules. I need to convert my old site's .htaccess to nginx syntax. I used an online syntax convertor and got this but it doesn't work. It tries to download the *.html file instead of parsing it as php and displaying it.

.htaccess

Options +FollowSymLinks -MultiViews

RewriteEngine On

RewriteCond %{HTTP_HOST}  www.example.com [nocase]
RewriteRule ^(.*)      http://example.com/$1 [last,redirect=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+).html$ index.php?q=$1 [L,QSA]

Broken code I tried to convert to nginx and i'm stuck on

location / { 
if ($http_host ~ "www.example.com"){ 
rewrite ^/(.*) http://example.com/$1 redirect; } 
if (!-e $request_filename){ 
rewrite ^/([^.]+).html$ /index.php?q=$1 break; } 
}
Was it helpful?

Solution

server_name example.com;
return 301 $scheme://www.example.com$request_uri;
if (!-e $request_filename)
{
    rewrite ^/([^.]+).html$ /index.php?q=$1 last;
}

OTHER TIPS

Have a look at try_files:

try_files $uri $uri/ /index.php?q=$uri&$args;

It will try each argument from left to right. If no file/directory is found it will default to /index.php with the uri and query string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top