HTACCESS Snippets
# HTACCESS
## Snippets
### Redirect all traffic to HTTPs
```
RewriteEngine On
# When the SSL certificate is not installed in the web server where the website is running.
# For example, when using Cloudflare's SSL or when the SSL certificate is installed in
# a load balancer but not in the web server.
RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteRule .* - [E=protossl:1]
# This only works if the certificate is installed in the web server.
RewriteCond %{HTTPS} on
RewriteRule .* - [E=protossl:1]
RewriteCond "%{ENV:protossl}" !=1
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
```
### Redirect all traffic to access the site WITH the 'www.' prefix.
```
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
```
### Redirect all traffic to access the site WITHOUT the 'www.' prefix.
```
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]
```
### Redirect path to another location
```
RewriteEngine On
RewriteCond %{REQUEST_URI} /my-url [NC]
RewriteRule .* https://domain.tld/123412341234/ [R=301,L]
```
### Redirect not-found requests to another server
```
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^images/(.+)$ https://domain.tld/images/$1 [R,L]
```
### Redirect not-found files calls to other host
```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/sites/default/files/.+$
RewriteCond %{HTTP_HOST} ^localhost
RewriteRule ^(.*)$ http://otherhost.com/$1 [L]
```
### Prevent access to certain files or directories
Prevent access to directories.
```shell
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
```
Prevent access to the a file.
```
<Files "config.json">
Deny from all
</Files>
```
Regular expressions can also be used, with the addition of the ~ character.
```
<Files ~ "config\.(json|yml)$">
Deny from all
</Files>
```
### Prevent directory listing
```
Options -Indexes
```
### Protect directory or files with password
You can use a free tool like: http://tools.dynamicdrive.com/password/
Or use this snippets:
First, create the credentials:
```
sudo htpasswd -c /var/www/.htpasswd myusername
```
Then, add this to the `.htaccess` file:
```
AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /var/www/.htpasswd
Require valid-user
```
## Tips
### Wrap the snippet inside "IfModule"
For mod_rewrite rules, you can use the IfModule clause to ensure this won't brake the website if the RewriteEngine module is not enabled:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} /my-url [NC]
RewriteRule .* https://domain.tld/123412341234/ [R=301,L]
</IfModule>
```