Skip to content

Instantly share code, notes, and snippets.

@mauricios
Last active November 30, 2016 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauricios/46cbb1195ea2a1f5c5b49edcb0da1c9c to your computer and use it in GitHub Desktop.
Save mauricios/46cbb1195ea2a1f5c5b49edcb0da1c9c to your computer and use it in GitHub Desktop.
Apache Rewrite rules to redirect hostnames
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect to WWW all domain variants but wwww variant
# Redirect all domains that include the keywords target-domain, redirect-domain1, redirect-domain2
# Excluding www.target-domain.com, www.no-redirect-domain1.com and www.no-redirect-domain2.com
# To www.target-domain.com
RewriteCond %{HTTP_HOST} ^(?!www\.target-domain\.com|.*\.no-redirect-domain1\.com)(.*\.|)(target-domain|redirect-domain1|redirect-domain2)\..*$ [NC]
RewriteRule ^(.*)$ http://www.target-domain.com$1 [R=301,L]
# Enforce HTTPS depending on an URL. Keeping the same path
# Useful for protected areas of the site
RewriteCond %{HTTPS} off
RewriteRule ^/path(|/.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Conditional redirect depending on a domain name
<If "%{HTTP_HOST} == 'www.domain.com'">
RedirectMatch ^/$ http://www.other_domain.com
Redirect "/path" "http://www.other_domain.com"
</If>
</IfModule>
@mauricios
Copy link
Author

mauricios commented Nov 5, 2016

How to test redirects:

  1. Install httpie : https://github.com/jkbrzt/httpie (for macOS brew install httpie)
  2. http --print=hb http://<apache_server_hostname>/<path> Host:<test_hostname> | egrep "^HTTP|^Location|<title>"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment