phpwordpressnginxngx-http-rewrite-module

Nginx: how do I rewrite a URL subdirectory to a query parameter?


I am trying to rewrite a URL in a WordPress website running Nginx so that the last subdirectory is transformed into GET-parameter:

http://mydomain/property/aid/1234/ to http://mydomain/property/?aid=1234/

I tried with add_rewrite_rule in WordPress, but it didn't work as it didn't create a new $_GET entry.

Then I tried the following Nginx rule:

rewrite ^(/property/.*)/aid/(.*)$ /$1/?aid=$2 break;

which seems to have no effect at all.

Any suggestions?


Solution

  • Suppose the document root is /www/yourproject/public. Then the configuration for PHP-FPM may look like the following:

    rewrite "^/property/aid/([0-9]+)$" /property/?aid=$1 break;
    
    location /property/ {
      root            /www/yourproject/public;
      fastcgi_pass    unix:/tmp/php-fpm-yourproject.sock;
      fastcgi_index   index.php;
      include         fastcgi_params;
    }
    

    In this configuration, the requests are processed by /www/yourproject/public/property/index.php.

    Sample index.php

    <?php
    var_dump($_GET);
    

    Sample output for /property/aid/1234

    array(1) {
      ["aid"]=>
      string(4) "1234"
    }
    

    You can replace fastcgi_pass and fastcgi_index directives with a proxy_pass, for instance.