Introduction
This is a quick tutorial how to set Nginx Rewrite Rules for Pretty URLs on WordPress. We’ll help you resolve the issue associated with Nginx rewrite rules.
NGINX Rewrite Rules
If your website is running on Apache, you don’t have to worry about the rewrite rules as the Apache server handles the process of writing suitable rewrite rules within your .htaccess
file, and all of the urls will work like a charm. Apache is great!
But, many of us become frustrated when website is running on Nginx web server, because we encounter the “404 error” problem. Regardless, we still want Nginx because it’s more powerful in performance. No problem. All we have to do is just to add a few new rules within Nginx configuration file.
Configure WordPress NGINX Rewrite Rules
Hopefully you have already setup Nginx server. Otherwise, please check the official Nginx Getting Started page. Here is the entire config file, at least it should look like this:
server { ## Your website name goes here. server_name domain.tld; ## Your only path reference. root /var/vhosts/yoursite; ## This should be in your http block and if it is, it's not needed here. index index.php; location =https://cdn.cyberpunk.rs/favicon.ico.gzip { log_not_found off; access_log off; } location = /robots.txt { allow all; log_not_found off; access_log off; } location / { # include the "?$args" part so non-default permalinks doesn't break when using query string try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { try_files $uri =404; include fastcgi_params; # With php7.0-cgi alone: # fastcgi_pass 127.0.0.1:9000; # With php7.0-fpm: fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www/vhosts/youtsite$fastcgi_script_name; fastcgi_split_path_info ^(.+\.php)(/.+)$; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires max; log_not_found off; } }
With this configuration everything should work. Of course, you need to know that it depends on server configuration. For Multisite and Multisite using subdomains configurations check here.
Try to understand before you just copy and paste. So, let’s explain:
index index.php
is specifying all the default files for execution, to explore the directories;
location /
directive location (searching for requests only for /yoursite;
try_files
directive will try to find does particular file or folder ($uri
$uri/
) exists. If not, /index.php
will be used as default file to run (we are then able to remove index.php
form path).
Once you’ve setup configuration file, don’t forget to reload Nginx:
service nginx reload
That’s it! It’s ready, let’s make URLs “pretty”.
- Login to your WordPress Admin
- Navigate to Settings > Permalinks
- In the “Custom Structure” text field, enter in /%postname%/
- Click the “Save Changes” button
For more info about WordPress on Nginx web server, check this Nginx rewrite rules docs. You may also be interested in How to Add Bootstrap to WordPress Theme.