Blog / WordPress/ Essential WordPress URL Rewrite Rules for Nginx, LiteSpeed, and Lighttpd

Essential WordPress URL Rewrite Rules for Nginx, LiteSpeed, and Lighttpd

WordPress 在 Nginx、LiteSpeed 与 Lighttpd 服务器下的 URL 重写规则详解

Introduction

For WordPress permalinks to function correctly, your web server must be configured with appropriate URL rewrite rules. This guide provides the essential configurations for Nginx, LiteSpeed, and Lighttpd servers.

Nginx Configuration

Add the following directive inside your site's location / { ... } block in the Nginx configuration file (commonly nginx.conf or a site-specific include):

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

How it works: The try_files directive attempts to serve the requested file or directory. If neither exists, it passes the request to /index.php, preserving any query string arguments.

Best practice: Avoid older configurations that rely on if statements or complex rewrite rules, as they can introduce performance issues and unexpected behavior.

LiteSpeed Configuration

LiteSpeed is compatible with Apache's .htaccess files. Place these rules in the .htaccess file located in your WordPress root directory:

RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

How it works: This enables the rewrite engine and redirects any request for a non-existent file or directory to /index.php. WordPress often generates these rules automatically when you save your permalink settings.

Lighttpd Configuration

Add these rules to your Lighttpd configuration (lighttpd.conf or an included snippet) within a url.rewrite-if-not-file block:

url.rewrite-if-not-file = (
    "^/(wp-(content|admin|includes).*)" => "$0",
    "^/(.*.(php|css|js|png|jpg|jpeg|gif|ico|xml))$" => "$0",
    "^/(sitemap.xml)$" => "$0",
    "^/(xmlrpc.php)$" => "$0",
    "^/(.*)$" => "/index.php/$1"
)

How it works: These rules allow direct access to WordPress core directories, static asset files, sitemap.xml, and xmlrpc.php. All other requests are internally rewritten to /index.php with the original path appended as a parameter.

General Notes and Best Practices

  • Always Backup: Create a backup of your server configuration files before making any changes.
  • Restart Services: After modifying Nginx or Lighttpd main configuration files, restart or reload the service. Changes to .htaccess files (LiteSpeed/Apache) take effect immediately.
  • WordPress Permalink Setup: In your WordPress admin, navigate to Settings > Permalinks and select any structure other than "Plain" to activate URL rewrite functionality.

Correct URL rewrite configuration is essential for a fully functional WordPress site. Use the method that corresponds to your web server software.

Post a Comment

Your email will not be published. Required fields are marked with *.