Skip to content

Instantly share code, notes, and snippets.

@mttjohnson
Created December 9, 2015 18:48
Show Gist options
  • Save mttjohnson/b3d72cdb45e98c62d6f2 to your computer and use it in GitHub Desktop.
Save mttjohnson/b3d72cdb45e98c62d6f2 to your computer and use it in GitHub Desktop.
mod_rewrite RewriteRule - Redirects
<IfModule mod_rewrite.c>
RewriteEngine on
############################################
## Define some initial variables for use in RewriteRules later
## Sets an env var on secure page loads for www redirects ##
RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} https [NC]
RewriteRule ^(.*)$ - [E=SECURE:s]
# Capture some variables from the current hostname
# Current Sub Domain = C_SUB_D
# Current TLD (Top Level Domain) = C_TLD
RewriteCond %{HTTP_HOST} ([^.]+\.)*([^.]+)\.([^.]+)$
RewriteRule ^(.*)$ - [E=C_SUB_D:%1,E=C_TLD:%3]
# set some host and site variables
RewriteRule ^(.*)$ - [E=HOST_FIRST:%{ENV:C_SUB_D}firstdomain.%{ENV:C_TLD}]
RewriteRule ^(.*)$ - [E=HOST_SECOND:%{ENV:C_SUB_D}seconddomain.%{ENV:C_TLD}]
RewriteRule ^(.*)$ - [E=SITE_FIRST:http%{ENV:SECURE}://%{ENV:C_SUB_D}%{ENV:HOST_FIRST}.%{ENV:C_TLD}]
RewriteRule ^(.*)$ - [E=SITE_SECOND:http%{ENV:SECURE}://%{ENV:C_SUB_D}%{ENV:HOST_SECOND}.%{ENV:C_TLD}]
# Redirects the URL to the same address at *.firstdomain.*/
#RewriteRule ^(.*)$ http%{ENV:SECURE}://%{ENV:HOST_FIRST}/$1 [R=301,L]
#RewriteRule ^(.*)$ %{ENV:SITE_FIRST}/$1 [R=301,L]
# Redirects the URL to the same address at *.seconddomain.*/
#RewriteRule ^(.*)$ http%{ENV:SECURE}://%{ENV:HOST_SECOND}/$1 [R=301,L]
#RewriteRule ^(.*)$ %{ENV:SITE_SECOND}/$1 [R=301,L]
# This works well for building redirects for site that you may have setup in
# multiple environments like dev, stage, prod
# dev.firstdomain.com, firstdomain.dev, www.firstdomain.dev, stage.firstdomain.com, www.firstdomain.com
# dev.seconddomain.com, seconddomain.dev, www.seconddomain.dev, stage.seconddomain.com, www.seconddomain.com
# you can use these rules in a .htaccess file that is used by multiple domains and check
# the current host as a condition to forward certain paths over to the other site's url
</IfModule>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment