What would be the nginx rewrite rule to redirect my wordpress permalink structure from /%category%/%postname%/
to /%postname%/
?
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.
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.
URL link rewriting is an overly manual security control prone to human error.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With