User Tools

Site Tools


wiki:rewrite_rule_examples

Apache rewrite rule examples

Rewrite from one domain to other including the trailing slash

RewriteCond %{REQUEST_URI} ^pdf\.example\.com(/*)$ [OR]
RewriteRule ^ https://subdomain.newexample.com [NE,R=permanent]

This will rewrite “pdf.example.com” and “pdf.example.com/” to “https://subdomain.newexample.com” every time.

Forcing www for a domain while preserving subdomains

RewriteCond %{HTTP_HOST} ^([a-z.]+)?example.com$ [NC]
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule .? http://www.%1example.com%{REQUEST_URI} [R=301,L]

This rule captures the optional subdomain using the %1 variable, and, if it doesn’t start with www., redirects with www. prepended to the subdomain. The domain and the original {REQUEST_URI} are appended to the result.

Eliminating www from a domain

RewriteCond %{HTTP_HOST} !^example.com$ [NC]
RewriteRule .? http://example.com%{REQUEST_URI} [R=301,L]

Getting rid of the www but preserving a subdomain

RewriteCond %{HTTP_HOST} ^www.(([a-z0-9_]+.)?example.com)$ [NC]
RewriteRule .? http://%1%{REQUEST_URI} [R=301,L]

Here, the subdomain is captured in %2 (the inner capture group) but, since it’s optional and already captured in the %1 variable, all you need is the %1 for the subdomain.

More at https://www.sitepoint.com/apache-mod_rewrite-examples-2

Tested on

See also

References

wiki/rewrite_rule_examples.txt · Last modified: 2021/07/09 10:07 by antisa

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki