• I would like to make rewrite in nginx for search pages URL from a standard “/?s=<text>” to “/search/text”. It’s important to make it in nginx, but not with the help of changing search slug in theme functions or with the help of plugin.

    Please could you suggest a proper way of doing that?

Viewing 1 replies (of 1 total)
  • I’m no expert with this, but you maybe can achieve this by using Nginx’s rewrite rules in your server block configuration.

    You could try rewriting the search URLs from the standard /?s=<text> format to the desired /search/text format like so:

    server {
        # ... other server configuration ...
    
        location / {
            # ... other location settings ...
    
            if ($args ~ "^s=(.*)$") {
                set $search_query $1;
                rewrite ^ /search/$search_query? permanent;
            }
        }
    
        location /search/ {
            # ... other location settings ...
    
            try_files $uri $uri/ /index.php?$args;
        }
    
        # ... other server configuration ...
    }

    Explanation:

    1. In the location / block, you use an if condition to capture the search query parameter using a regular expression match on the $args variable. If the condition is met, the search query is stored in the $search_query variable.
    2. You then use the rewrite directive to perform a permanent (301) redirect to the desired /search/text format, where $search_query is the captured query parameter.
    3. In the location /search/ block, you use the try_files directive to handle requests for the rewritten URLs. This will try to find a matching file, and if not found, will pass the request to WordPress’s index.php along with the query string.

    Please make sure to replace the comments like # ... other server configuration ... with your actual server and location block settings. Also, be cautious when using if directives in Nginx, as they can have performance implications if not used carefully. In this case, the if directive is used to handle the search query parameter rewriting and should work as intended.

    I hope this points you in the right direction…

Viewing 1 replies (of 1 total)
  • The topic ‘Nginx redirect for search pages’ is closed to new replies.