A
A
Alexey2020-02-27 17:25:39
Nginx
Alexey, 2020-02-27 17:25:39

How to convert rewrite rule from htaccess to nginx?

The task seems to be simple, but I haven’t set up the server for a very long time and I just can’t figure it out. I am moving a PHP site to another server, but I need to use Nginx instead of Apache. There are many .htaccess files in the directories with the following content:

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


For example, public_html/api/v2/.htaccess and in the same directory is index.php, which should be redirected to everything that comes from the url of the same name.

Now my Nginx config looks something like this:
server {
        listen       443 ssl;
        server_name  site.io;
        access_log  off;
        
        ssl_certificate      "/var/node/********.crt";
        ssl_certificate_key  "/var/node/********.key";


        location / {
            root   /var/www/service/public_html;
            index  index.php index.html index.htm;
        }

        location /api/v2 {
            rewrite ^(.+)$ /api/v2/index.php?q=$1;
        }

        location ~ \.php$ {
            root           /var/www/service/public_html;
            fastcgi_pass   127.0.0.1:9001;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }


The request https://site.io/api/v2/dashboard?dateFrom=2020-02-... should work, but it returns a 404 error.
What needs to be changed in the config to make this request work?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2020-02-27
@Espritto

server {
        listen       443 ssl;
        server_name  site.io;
        access_log  off;
        
        ssl_certificate      "/var/node/********.crt";
        ssl_certificate_key  "/var/node/********.key";

        root   /var/www/service/public_html;

        location / {
            index  index.php index.html index.htm;
        }

        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9001;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

        location ~ ^/api/v2/(.+) {
            try_files $uri /api/v2/index.php?q=$1&$args;
        }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question