Skip to main content

Rewrite Rules

Learning Focus

By the end of this lesson you will understand how rewrite rules work in OpenLiteSpeed, common patterns for PHP applications, and how to test them.

What Rewrite Rules Do

Rewrite rules transform incoming URLs before they reach the application. They are commonly used for:

  • Clean/pretty URLs (e.g., /blog/my-post instead of /index.php?p=123)
  • CMS routing (WordPress, Laravel, Drupal)
  • URL canonicalization (removing trailing slashes, forcing www)
  • SEO-friendly URL patterns

Common Rewrite Patterns

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

Laravel Pretty URLs

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

Force www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Force HTTPS

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Rewrite Rules Location

LocationScopePerformance
WebAdmin (vhost config)Per virtual hostBetter (loaded once)
.htaccessPer directorySlower (read per request)

Testing Rewrites

# Check if a URL rewrites correctly
curl -sI http://example.com/my-pretty-url

# Enable rewrite logging temporarily in WebAdmin
# Virtual Host → Rewrite → Log Level → set to 5
# Then check:
tail -50 /usr/local/lsws/logs/error.log | grep -i rewrite
info

OpenLiteSpeed supports most Apache-style rewrite rules. If a rule doesn't work, check the error log with rewrite logging enabled.

Key Takeaways

  • Rewrite rules transform URLs for clean routing, SEO, and protocol enforcement.
  • Place rewrites in vhost config for better performance over .htaccess.
  • Use rewrite logging to debug rules that don't work as expected.

What's Next

  • Continue to Redirects for URL redirect patterns.