WordPress Permalink Rewrite Rules for Nginx and Apache (Including Subdirectory Configs)
Among various CMS programs, WordPress is widely used not only for its strong security but also for its extensive library of plugins and themes, making it easy for users without technical skills to build their own websites. To create value, a website needs traffic, whether through revenue or user appreciation. In the past, dynamic directory pages were common, but they are not ideal for search engines. Therefore, using pseudo-static URLs or generating static pages is recommended.
When applying WordPress, pseudo-static rules must be configured based on the server environment. Nginx and Apache are the most common servers, and the corresponding rule codes are outlined below.
1. Apache Environment
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
This code is suitable for the Apache environment. Simply place it in a .htaccess file in the root directory.
2. Nginx Environment
location / {
if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}
if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}
if (!-f $request_filename){
rewrite (.*) /index.php;
}
}
Virtual hosts typically use Apache, while VPS environments often use Nginx. For Nginx, apply this rule to the site's configuration file, for example: /usr/local/nginx/conf/wordpress.conf.
Then, reference this file in the main site configuration, such as /usr/local/nginx/conf/vhost/hostusvps.com.conf:
server {
listen 80;
server_name hostusvps.com www.hostusvps.com;
access_log /home/wwwlogs/hostusvps.com_nginx.log combined;
index index.html index.htm index.php;
include wordpress.conf;
root /home/wwwroot/hostusvps.com;
location ~ .*\.(php|php5)?$ {
#fastcgi_pass remote_php_ip:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
}
The highlighted include wordpress.conf; line in the script above is where the pseudo-static rule is referenced.
3. Subdirectory Rules
If you are running a separate WordPress instance in a subdirectory folder of your site, the rules differ.
location /hostusvps.com/ {
index index.html index.php;
if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}
if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}
if (!-f $request_filename){
rewrite (.*) /hostusvps.com/index.php;
}
}
In this example, the path corresponds to the hostusvps.com subdirectory folder. If using a different folder name, update the path accordingly. You can modify and add these rules to the .htaccess file in the root directory for Apache or the Nginx configuration for Nginx.