Tag Archives: .htaccess

Apache Rewrite rules

Rewrite rules examples:

This can be added in vhost configuration OR in .htaccess file

How to rewrite all web request on my site without www to www.domain.com

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule (.*) http://www.example.com$1 [R,L]

 

How to redirect all web requests on port 80 (or HTTP) to port 443 (HTTPS)

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

 

How to disable TRACE and TRACK methods on Apache

RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]

 

How to exclude mod_status from being rewritten by existing rules (placed before the problem rule)

RewriteCond %{REQUEST_URI} !=/server-status

 

How do I redirect all web requests on www.mysite.net/web to www.mysite.net/sect1/web

RewriteCond %{http_host} ^[www\.]*example\.com
RewriteRule ^web(/)?$ /sect1/web [R=301,L]

 

Rewrite all non-www to www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

 

Force all URLs to be lowercase

RewriteEngine On
RewriteMap lc int:tolower
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule (.*) ${lc:$1} [R=301,L]

 

Apache .htaccess for website password authentication

Quick notes… the ones that you are probably forgetting if you’re not using it….

Go inside your website folder website

Create a .htaccess file with the below content

AuthUserFile /var/www/website/.htpasswd
AuthGroupFile /dev/null
AuthName "Work forms"
AuthType Basic
require valid-user

Make sure the permissions are set correctly:

chmod ugo+r .htaccess

Then, create the user and the password:

htpasswd -c /var/www/website/.htpasswd your_user

Please note that the -c is to “create” the file. If you want to add other users, just remember to remove that flag or the file will be overwritten

In the VirtualServer section, make sure to have this:

<Directory "/var/www/<website>">
AllowOverride AuthConfig
</Directory>

Restart apache and… it should work 😛