Home > Back-end >  How to write an NGINX rewrite which strips out everything from the URL after /filters/
How to write an NGINX rewrite which strips out everything from the URL after /filters/

Time:12-13

We're running a Symfony application, which has a route of: domain.tld/main-category/category/

For SEO purposes, they want to include filters in the URL like this: domain.tld/main-category/category/filters/price:0-100

So basically we want the URL in the browser to remain the same, but in Symfony it should strip out everything after and including /filters/. So the route should remain "domain.tld/main-category/category/".

I tried this which does work, however I need it to work using Symfony routes but could not get it to work.

rewrite ^/.*/filters/.* /test.html last;

NGINX config:

location ~ ^/index\.php(/|$) {
    include fastcgi_params;
    fastcgi_pass php_project:9000;
    fastcgi_read_timeout 600s;
    fastcgi_split_path_info ^(. \.php)(/.*)$;

    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
    internal;
}

CodePudding user response:

DISCLAIMER: This is a bit of a guess and might not work for you

PHP applications such as index.php often use the REQUEST_URI parameter to determine the "route". This is defined within your fastcgi_params file as:

fastcgi_param REQUEST_URI $request_uri;

One solution could be to manipulate this value using a map directive.

For example:

map $request_uri $myroute {
    default                      $request_uri;
    ~*^(?<newroute>/.*)/filters/  $newroute;
}
server {
    ...
    location ~ ^/index\.php(/|$) {
        include fastcgi_params;
        fastcgi_pass php_project:9000;
        fastcgi_read_timeout 600s;
        fastcgi_split_path_info ^(. \.php)(/.*)$;
    
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        fastcgi_param REQUEST_URI $myroute;
        internal;
    }
}

Note that the map must be placed outside of the server block.

You do not need to edit the fastcgi_params file, simply ensure that the fastcgi_param statements appear in the location block after the include statement.

  • Related