htaccess

What is .htaccess

.htaccess is a configuration file for the Apache web server. It’s an extremely powerful tool that can be used to modify the Apache configuration without needing to edit the Apache configuration files.

Error pages

#Unauthorized
ErrorDocument 401 /htaccess/401.html
#Page not found error
ErrorDocument 404 /htaccess/404.html
#Internal Server Error
ErrorDocument 500 /htaccess/500.html

Redirect

Redirect /old_dir/ http://www.yourdomain.com/new_dir/index.html

Password protected directory

#These code should lie inside the a directory which will be
#password protected.
#First line is the title of the popup.
#Second line contains the absolute path of the file
#that contains username and encryptedpassword as like below:
#username:encryptedpassword
#rejauldu:163884

#In windows server password will be normal text.
#In UNIX/LINUX password will be encrypted.
#Third and fourth line will not be changed.

AuthName "Member's Area Name"
AuthUserFile C:\xampp\htdocs\wp-content/.htpasswd
AuthType Basic
require valid-user

Allowing/Denying by ip address

#This code should lie inside the directory
#which will be allowed or denied by IP
#In (order allow, deny) allow will be evaluated first then deny.
#In (order deny, allow) deny will be evaluated first then allow.
#Blocked visitors will be shown a '403 Forbidden' error message.

order allow,deny
#deny from 127.0.0.1
deny from 123.45.6.
allow from all
The following code will cause a 404 error to appear if anybody attempts to view the file wp-config.php
<Files ~ "/wp-config.php">
Order Allow,Deny
Deny from All
</Files> 

Rewrite Rules

This functionality requires that 'mod_rewrite' is enabled on your server. Few code are given below and their explanation will be given accordingly.

Block referer

RewriteEngine on
Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} otherdomain\.com [NC]
RewriteRule .* - [F]

Redirecting using rewrite rule 

This .htaccess file will redirect http://example.com/folder1/ to http://example.com/folder2/.
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^folder1.*$ http://example.com/folder2/ [R=301,L]

This .htaccess file will redirect http://example.com/folder1/ to plain http://example.com/.
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^folder1.*$ http://example.com/ [R=301,L]

This .htaccess file will redirect http://example.com/folder1/file.html to http://example.com/folder2/file.html. 
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^folder1/(.*)$ http://gs.mt-example.com/folder2/$1 [R=301,L]

This .htaccess file will redirect http://example.com/file.html to http://example.com/folder1/file.html.
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} example.com$ [NC] #URL must start with example.com
RewriteCond %{HTTP_HOST} !folder1 #URL should not contain folder
RewriteRule ^(.*)$ http://example.com/folder1/$1 [R=301,L]

This .htaccess file will redirect http://example.com/ to http://www.example.com/.
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

This .htaccess file will redirect http://example.com/ to https://example.com/.
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
Another example to force https:
RewriteEngine OnRewriteCond %{HTTPS} !=onRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

Explanation
  • Options +FollowSymLinks is an Apache directive, prerequisite for mod_rewrite.
  • RewriteEngine On enables mod_rewrite.
  • RewriteRule defines a particular rule.
  • The first string of characters after RewriteRule defines what the original URL looks like.
  • The second string after RewriteRule defines the new URL.
  • $1 at the end matches the part in parentheses () from the first string. Basically, this makes sure that sub-pages get redirected to the same sub-page.
  • RewriteCond %{HTTP_HOST} shows which URLs we do and don't want to run through the rewrite.
  • RewriteRule defines a particular rule.

Flags
  • [R=301,L] This flag mean 301 redirect, last rewrite rule
  • [NC] This flag mean Not case-sensative
  • [F] Displays Forbitten error 403

RewriteRule vs. Redirect

Redirect is a client-side request to have the web browser go to another URL. This means that the URL that you see in the browser will update to the new URL.
RewriteRule is a server-side rewrite of the URL before it’s fully processed by IIS. This will not change what you see in the browser because the changes are hidden from the user.

Hot link prevention

The following lines tell the Apache Web Server to block all links to '.gif', '.jpg' and '.css' files which are not from the domain name 'http://www.yourdomain.com/'. This is called hot link prevention.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(gif|jpg|css)$ - [F]

The following lines tell the Apache Web Server to block all links to '.gif' and '.jpg' files which are not from the domain name 'http://www.yourdomain.com/' and to display the file 'http://www.yourdomain.com/hotlink.jpg' instead.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.yourdomain.com/hotlink.jpg [R,L]

DirectoryIndex uses


The following lines tell the Apache Web Server to display the 'index.html' file.
DirectoryIndex index.html

The following lines tell the Apache Web Server to display the 'index.html' file as the directoryindex, if this file is not available then display 'index.cgi', and if this is not available then display 'index.php'.
DirectoryIndex index.html index.cgi index.php

Adding MIME types


'AddType' specifies that you are adding a MIME type. The second part is the MIME type, in this case text or HTML, and the final part is the file extension, in this example 'htm0'.
AddType text/html htm0 #AddType MIME-Type extension

A common issue with MP3 or SWF files not playing can be resolved with the following text.
AddType application/x-shockwave-flash swf

Note: A handy trick, to force a file to be downloaded, via the 'Save As' feature in the web browser, set the MIME type to application/octet-stream and the browser will immediately prompt for download.

Directory listing

To prevent directory listings (hiding file names)
IndexIgnore *
or to give a forbidden message,
Options -Indexes
To hide only '.zip' files
IndexIgnore *.zip
To prevent listing multiple file types
IndexIgnore *.zip *.jpg *.gif
Alternatively, if your server does not allow directory listings and you would like to enable them
Options +Indexes

Setting server timezone

To set your web servers date timezone, for example, for Los Angeles time (Pacific time), use the following code:
SetEnv TZ America/Los_Angeles

Forcing scripts to display as source code

If you need to display scripts as source code, instead of executing use this code:
RemoveHandler cgi-script .pl .cgi .php .py
AddType text/plain .pl .cgi .php .py

Ensuring media files are downloaded instead of played

It is possible to ensure that any media files are treated as a download, rather than to be played by the browser. Use:
AddType application/octet-stream .zip .mp3 .mp4
Reference:
http://www.htaccess-guide.com/deny-visitors-by-referrer/
https://mediatemple.net/community/products/dv/204643270/using-htaccess-rewrite-rules
WordPress .htaccess link

Remove .php extension

#Adding a .php extension to all http requests
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ $1.php [NC,L]
or,
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Reference: https://alexcican.com/post/how-to-remove-php-html-htm-extensions-with-htaccess/

Sending all requests to index.php

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
use $_GET['path'] to get the requested url.
or,
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
use $_SERVER['REQUEST_URI'] to get the requested url.
The flags:
NC = No Case (not case sensitive, not really necessary since there are no characters in the pattern)
L = Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)
QSA = Query String Append, just in case you've got something like ?like=penguins on the end which you want to keep and pass to index.php.
Reference: https://stackoverflow.com/questions/18406156/redirect-all-to-index-php-using-htaccess

Sending all requests to routes.php
RewriteEngine onRewriteRule ^$ /routes.php [L,QSA]
RewriteEngine onRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^.*$ /routes.php [L,QSA]

Redirect to public as root - Laravel

RewriteEngine On
# Map https://stading.themovers.my to /public.
RewriteRule ^$ /public/ [L]
# Map https://stading.themovers.my/x to /public/x unless there is a x in the web root.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1
# Add trailing slash to directories within public
# This does not expose the internal URL.
RewriteCond %{SCRIPT_FILENAME} -d
RewriteRule ^public/(.*[^/])$ ./$1/ [R=301]

Enable gzip compression

<IfModule mod_deflate.c>
# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml

# Remove browser bugs (only needed for really old browsers)
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>

Caching files to browser

<IfModule mod_expires.c>
ExpiresActive On

# Images
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"

# Video

ExpiresByType video/mp4 "access plus 1 year"
ExpiresByType video/mpeg "access plus 1 year"

# CSS, JavaScript
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"

# Others
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType application/x-shockwave-flash "access plus 1 month"
</IfModule>

Labels:

© copyright-2020 Rejaul