Andres Gonzalez
Andres Gonzalez

Reputation: 33

Convert Apache rewrite to Nginx

I have this htaccess code:

RewriteEngine On
​
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
​
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

i wanna convert to nginx rewrite rules, i tried with

if (!-e $request_filename){
     rewrite ^(.+)$ /index.php?url=$1 break;
}

But it doesn't work, any idea ?

Upvotes: 1

Views: 1760

Answers (2)

WLFree
WLFree

Reputation: 119

Convert your .htaccess for nginx. I just switched from Apache 2.4 to Nginx 1.18.0 and it works, but all rewrite lines should be inside your server block in nginx conf, otherwise it converts it all.

https://winginx.com/en/htaccess

Upvotes: 0

Richard Smith
Richard Smith

Reputation: 49692

The equivalent rewrite would be:

if (!-e $request_filename){
    rewrite ^/?(.*)$ /index.php?url=$1 last;
}

As nginx URIs include the leading / which your script probably does not want. Also, the .php file is likely processed in a different location block, so you need to use last.

Alternative ways of writing this without the use of an if block:

First, with the leading /:

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

Second, without the leading /:

location / {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
    rewrite ^/?(.*)$ /index.php?url=$1 last;
}

All nginx directives are documented here.

Upvotes: 1

Related Questions