Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGINX rewriting rule for getting clean URL

What would be the nginx rewrite rule to redirect my wordpress permalink structure from /%category%/%postname%/ to /%postname%/?

like image 311
Joel Avatar asked Jan 23 '12 05:01

Joel


People also ask

How do I rewrite rules in nginx?

The syntax of rewrite directive is: rewrite regex replacement-url [flag]; regex: The PCRE based regular expression that will be used to match against incoming request URI. replacement-url: If the regular expression matches against the requested URI then the replacement string is used to change the requested URI.

What is a URL rewrite rule?

A rewrite rule defines the logic of what to compare or match the request URL with, and what to do if the comparison is successful. Rewrite rules consists of the following parts: Pattern – The rule pattern is used to specify either the regular expression or a wildcard pattern that is used to match URL strings.

Is URL rewriting safe?

URL link rewriting is an overly manual security control prone to human error.


1 Answers

In summary, you need to let NGINX know that if that file doesn't exist, to not throw a 404 error, but rather call index.php. Wordpress is smart enough to parse the URL as parameters, and serve the correct page.

Add this snippet in your server configuration block:

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

Here is a complete example from nginx.org:

# Upstream to abstract backend connection(s) for php
upstream php {
        server unix:/tmp/php-cgi.socket;
        server 127.0.0.1:9000;
}

server {
        ## Your website name goes here.
        server_name domain.tld;
        ## Your only path reference.
        root /var/www/wordpress;
        ## This should be in your http block and if it is, it's not needed here.
        index index.php;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        location / {
                # This is cool because no php is touched for static content.
                # include the "?$args" part so non-default permalinks doesn't break when using query string
                try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
                #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
                include fastcgi.conf;
                fastcgi_intercept_errors on;
                fastcgi_pass php;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }
}
like image 59
ryebread Avatar answered Sep 28 '22 08:09

ryebread