Htaccess tricks

From Wiki
Jump to: navigation, search

Block IP:

<RequireAll>
    Require all granted
    Require not ip 1.2.3.4
</RequireAll>

Force www, or non www, redirect.

#Force www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]#Force www:

#Force non-www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Redirect all traffic to SSL site.

RewriteEngine on
RewriteCond %{SERVER_PORT} !443 [NC]
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L,QSA]

Redirect based on referrer.

For example, to redirect the Globalsign verification bot.

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} GlobalSign-Approver-URL-Domain-Control-Verification-Agent-www.globalsign.com
RewriteRule .* /globalsign.html [R]

globalsign.html should look like this.

<html>
<head>
<meta name="globalsign-domain-verification" content="content" />
</head>
</html>

Redirect iPhones:

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} iPhone
RewriteCond %{REQUEST_URI} !^/my-iPhone-site/ 
RewriteRule .* /my-iPhone-site/ [R]

Block access by file extension:

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

Or:
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$">
Order Allow,Deny
Deny from all
</FilesMatch>

Redirect based on query string:

RewriteCond %{QUERY_STRING} option=com_xius&view=list&listid=19&task=showList&Itemid=3163 [NC]
RewriteRule ^index.php http://www.example.com/page-name [QSD,L,R=301]

http://www.philipphoffmann.de/blog/2012/08/16/how-to-discard-the-query-string-in-a-rewriterule-apache-mod_rewrite/

Password protect directory using 2.4 directives:

<RequireAny>
  <RequireAll>
    AuthType Basic
    AuthName "Password Protected"
    AuthUserFile /home/perfumes/.htpasswds/public_html/devspace/passwd
    Require valid-user
  </RequireAll>
</RequireAny>

For Apache 2.2 Just remove the "Require" lines:

AuthType Basic
AuthName "Password Protected"
AuthUserFile /home/perfumes/.htpasswds/public_html/devspace/passwd
Require valid-user

Redirect old domain to a new domain.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example2.com/$1 [L,R=301,NC]
RewriteEngine On
RewriteRule ^ftp/pub/(.*)$ /repos/$1 [NC,L]
RewriteRule ^pub/(.*)$ /repos/$1 [NC,L]