optimize mod_rewrite in htaccess

Posted by clarkk on Server Fault See other posts from Server Fault or by clarkk
Published on 2012-03-27T11:21:20Z Indexed on 2012/03/27 11:31 UTC
Read the original article Hit count: 217

Filed under:
|
|

I got some mod_rewrite conditions in a .htaccess file which I have extended from time to time.. But I don't think its very well written (I'm still quite new to mod_rewrite)

Some times requests end up in infinite loops

And just now I added SSL to the file..

When requesting https:// I get a 404 error The requested URL /_secure/_secure/ was not found on this server. Somehow it adds an extra _secure to the path?

.htacces

#   set language
RewriteCond %{HTTP_HOST}        ^www\. [NC]
RewriteCond %{REQUEST_URI}      ^/(da|en)/(.*)(\?%{QUERY_STRING})?$ [NC]
RewriteRule ^(.*)$              /%2?%{QUERY_STRING}&set_lang=%1 [L]

#   put 'www' as subdomain if none is given
RewriteCond %{HTTP_HOST}        ^([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^(.*)$              http://www.%1/$1 [L,R=301]

#   rewrite subdomain
RewriteCond %{HTTP_HOST}        ^(admin|files)\.[^\.]+\.[^\.]+$ [NC]
RewriteCond %{REQUEST_URI}      !^/_(admin|files)/ [NC]
RewriteRule ^(.*)$              /_%1/$1 [L]

#   redirect to subdomain
RewriteCond %{HTTP_HOST}        ^www\.([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^_([^/]+)/          http://$1.%1/ [L,R=301]

#   start SSL on 'secure' subdomain if not started
RewriteCond %{HTTPS}            !=on
RewriteCond %{HTTP_HOST}        ^(secure)\.([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^(.*)$              https://%1.%2/$1 [L,R=301]

#   rewrite 'secure' subdomain
RewriteCond %{HTTP_HOST}        ^(demo|secure)\.[^\.]+\.[^\.]+$ [NC]
RewriteCond %{REQUEST_URI}      !^/_secure/ [NC]
RewriteRule ^(.*)$              /_secure/$1 [L]

#   rewrite 'api' subdomain
RewriteCond %{HTTP_HOST}        ^api\.[^\.]+\.[^\.]+$ [NC]
RewriteCond %{REQUEST_URI}      !^/_api/ [NC]
RewriteRule ^(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?(?:([^/]+)/)?             /_api/?%{QUERY_STRING}&v=$1&i=$2&k=$3&a=$4&t=$5&f=$6 [L]

#   redirect non-active subdomain to 'www'
RewriteCond %{HTTP_HOST}        !^(admin|api|demo|files|secure|www)\.([^\.]+\.[^\.]+)$ [NC]
RewriteRule ^(.*)$              http://www.domain.com [L,R=301]

#   hide file extensions
RewriteCond %{HTTP_HOST}        ^www\. [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\.php$ [NC]
RewriteCond %{REQUEST_URI}      ^/([^/]*)/(?:([^/]*)/)?(?:([^/]*)/)?$ [NC]
RewriteRule ^(.*)$              /%1.php?%{QUERY_STRING}&subpage=%2&subsection=%3 [L]

© Server Fault or respective owner

Related posts about apache2

Related posts about .htaccess