Several Tricks of .htaccess that can solve your life on the Web

Several Tricks of .htaccess that can solve your life on the Web

In this small tutorial we are going to show some tricks of configuration of .htaccess, the majority will solve the life on the Web to you.

We begin

To force that all the URL begins by www

This configuration only works for the URL nonsafe that they begin by http://:

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

This configuration works as much for the URL safe (https://) as for the URL normal (http://):

RewriteCond % \ {HTTP_HOST}! ^$ RewriteCond % \ {HTTP_HOST}! ^www \. [NC] RewriteCond % \ {HTTPS} s ^on (s)| RewriteRule ^ http%1: //WWW,% \ {HTTP_HOST} % \ {REQUEST_URI} [R=301, L]

To force that no URL begins by www

This configuration only works for the URL nonsafe that they begin by http://:

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

To force to that all the URL is safe and begins by https

RewriteEngine on RewriteCond % \ {HTTPS}! on RewriteRule (. *) https://% \ {HTTP_HOST} % \ {REQUEST_URI}

To force to that all the URL ends the bar/

RewriteCond % \/+ {REQUEST_URI} [^ \.] +$ RewriteRule ^ (. + [^/]) $ % \ {REQUEST_URI}/[R=301, L]

Redirigir individual pages

Redirect 301 /pagina_antigua.html http://www.ejemplo.com/nueva_pagina.html Redirect 301 /pagina_antigua_2.html http://www.ejemplo.com/directorio/

Redirigir everything a website

Redirect 301/http://nuevo_sitio.com/

Although this simple configuration does not seem it, in fact all the old connections to the new site are being redirigiendo, not only the cover of the site.

Security

To prevent any access to a website

The following configuration prevents, without exception, all the connections to your website, reason why it is a fast form “to extinguish it? and to make it disappear of Internet:

Deny from All   # in Apache 2,4, uses following # Require all denied

To prevent any access except for those authorized

Order deny, allow Deny from All Allow from xxx.xxx.xxx.xxx   # in Apache 2,4, uses following # Require IP xxx.xxx.xxx.xxx

Xxx.xxx.xxx.xxx by the direction IP replaces from which you want to allow the access to the site. This configuration also supports the definition of ranks of directions IP.

To allow all the accesses except for those deprived of authority

The following configuration is the opposite of the shown configuration previously, since it allows the access from any direction IP except for the indicated ones explicitly:

Order deny, allow Allow from All Deny from xxx.xxx.xxx.xxx Deny from xxx.xxx.xxx.yyy   # in Apache 2,4, uses following # Require not IP xxx.xxx.xxx.xxx # Require not IP xxx.xxx.xxx.yyy

To prevent the access to the hidden archives and directories

The hidden archives and directories (that is to say, those whose name begins with a point) normally are not public, reason why the Web server would not have to serve them:

RewriteCond % \ {SCRIPT_FILENAME} - d [OR] RewriteCond % \ {SCRIPT_FILENAME} - f RewriteRule “(^|/) \.? - [F]

Among others, this configuration protects archives as .htaccess and .htpasswd and directories as .git and .hg.

If you prefer it, also you can give back an error of type 404 (Not Found) to confuse a little to the attackers more:

RedirectMatch 404/\. *$

To prevent that it is possible to be acceded to archives with sensible contents

The following extensions correspond to the archives that can contain sensible information, as for example: archives of log with detailed information of the servant (.log), backup copies created by publishers as Vi/Vim (.swp), console commandos (.sh), configuration files (.config.ini), etc.

<FilesMatch “(\. (BAK|config|dist|fla|Inc. |INI|log|psd|sh|SQL|swp)|~) $ " > Order allow, deny Deny from all Satisfy All </FilesMatch>

To prevent that the listing of contents of a directory can be seen

Options All - Indexes

To prevent that other websites connect to your images

The following configuration prevents that any external website can connect to your images for “robbing them to you?. It changes the ejemplo.com value by your own dominion, so that only your you can connect to your images:

RewriteEngine on RewriteCond % \ {HTTP_REFERER}! ^$ RewriteCond % \ {HTTP_REFERER}! ^http (s): /(www \.)? ejemplo.com [NC] RewriteRule \. (jpg|JPEG|png|GIF) $ - [NC, F, L]

To protect the access to a directory by means of password

First you must create a called file .htpasswd with the commando htpasswd. This file is due to keep in any directory who is not directly accessible by means of the Web server:

$ htpasswd - c /home/usuario/.htpasswd nombre_usuario

And now already you can use this file to protect with password the access to any directory:

AuthType BASIC AuthName “Safe Zone? AuthUserFile /home/usuario/.htpasswd Require to valid-user

To protect one or several archives by means of password

AuthName “Safe Zone? AuthType BASIC AuthUserFile /home/usuario/.htpasswd   <Files “archivo_secreto.zip " > Require to valid-user </Files>   <FilesMatch ^ (\ invoices \ d+ .pdf) $> Require to valid-user </FilesMatch>

To improve the yield of a webpage, To do that a webpage loaded faster.

To compress archives

<IfModule mod_deflate.c>   # Forzar compression also for the malformadas heads # http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping <IfModule mod_setenvif.c> <IfModule mod_headers.c> SetEnvIfNoCase ^ (Accept-EncodXng|X-CEPT-Encoding|15 xs \ {}|~ \ {15}|- \ {15}) $ ^ ((gzip|deflate) \ s*? \ s*) +|[X~-] \ {4.13} $ HAVE_Accept-Encoding RequestHeader append Accept-Encoding “gzip, deflate? env=HAVE_Accept-Encoding </IfModule> </IfModule>   # Comprimir the contents that are of anyone of these types <IfModule mod_filter.c> AddOutputFilterByType DEFLATE application/atom+xml \ application/Javascript \ application/json \ application/rss+xml \ application/vnd.ms-fontobject \ application/x-font-ttf \ application/x-Web-app-manifest+json \ application/xhtml+xml \ application/xml \ font/opentype \ image/svg+xml \ image/x-icon \ text/css \ text/HTML \ text/plain \ text/x-component \ text/xml </IfModule>   </IfModule>

To use the head You expire of HTTP

The head You expire of HTTP indicates to the navigator the date as of which a resource considers _“nonvalid? _and must return to ask for itself to the servant instead of to use directly from the cache.

The recommendation for many of the static archives (CSS, Javascript, images, etc.) consists of establishing a date of very distant expiration (1 year for example). However, if the names of the archives do not include information on their version, then it is better than the expiration is not so distant (1 week for example).

It uses the following configuration to indicate the date of expiration of all the habitual static archives of the applications Web:

<IfModule mod_expires.c> ExpiresActive on ExpiresDefault “Access extra 1 month?   # CSS ExpiresByType text/css “Access extra 1 to year?   # Related files to AJAX and Web Sockets ExpiresByType application/json “Access extra 0 seconds? ExpiresByType application/xml “Access extra 0 seconds? ExpiresByType text/xml “Access extra 0 seconds?   # Favicon ExpiresByType image/x-icon “Access extra 1 week?   # Component HTML (HTCs) ExpiresByType text/x-component “Access extra 1 month?   # HTML ExpiresByType text/HTML “Access extra 0 seconds?   # ExpiresByType Javascript application/Javascript “Access extra 1 to year?   # Manifest ExpiresByType application/x-Web-app-manifest+json “Access extra 0 seconds? ExpiresByType text/breaks-manifest “Access extra 0 seconds?   # Photos, videos and audio audio ExpiresByType/ogg “Access extra 1 month? ExpiresByType image/GIF “Access extra 1 month? ExpiresByType image/JPEG “Access extra 1 month? ExpiresByType image/png “Access extra 1 month? ExpiresByType video/mp4 “Access extra 1 month? ExpiresByType video/ogg “Access extra 1 month? ExpiresByType video/webm “Access extra 1 month?   # Channels RSS and Atom ExpiresByType application/atom+xml “Access extra 1 hour? ExpiresByType application/rss+xml “Access extra 1 hour?   # Sources Web ExpiresByType application/font-woff “Access extra 1 month? ExpiresByType application/vnd.ms-fontobject “Access extra 1 month? ExpiresByType application/x-font-ttf “Access extra 1 month? ExpiresByType font/opentype “Access extra 1 month? ExpiresByType image/svg+xml “Access extra 1 month? </IfModule>

To deactivate HTTP the ETag head

To eliminate HTTP the ETag head can be useful in some situations, since it prevents to proxys and the navigators to frisk the contents based on this head. Actually, this force to that proxys and navigators use in their place the heads Break-Control or Expires:

<IfModule mod_headers.c> Header unset ETag </IfModule> FileETag None

Other tricks

To define options of configuration PHP

Php_value uses the special directive and next, it indicates the name of the option and its separated value by a space:

php_value <nombre-opcion> <valor-opcion>

This example defines the maximum time of execution of _scripts_ PHP and the maximum size of the archives that can be raised:

# For example: php_value upload_max_filesize 30M php_value max_execution_time 600

Customized pages of error

ErrorDocument 400 /errores/error400.html ErrorDocument 401 /errores/error401.html ErrorDocument 403 /errores/error403.html ErrorDocument 404 /errores/error404.html ErrorDocument 500 /errores/error500.html

To force to that the navigator lowers a file instead of to show it

The following configuration does that all the archives of Markdown type (extension .md) unload instead of to be within the navigator. It changes to the extension .md by the extension of the archives that you want to force that they unload:

<Files *.md> ForceType application/Header octet-stream set Content-Disposition attachment </Files>

To allow the load of sources from different dominions

Due to the restrictions of Cross Resource Sharing, it is possible that some sources served through a CDN do not work in Firefox or Internet Explorer. In order to solve it, it uses the following configuration:

<IfModule mod_headers.c> <FilesMatch “\. (eot|otf|ttc|ttf|woff) $ " > Header set Access-Control “*? </FilesMatch> </IfModule>

To force the use of the UTF-8 codification

# Servir contained as type text/plain or text/HTML using the codification UTF-8 AddDefaultCharset utf-8   # Forzar the UTF-8 codification in several types of AddCharset archives utf-8 .atom .css .js .json .rss .vtt .xml

Abimael Gutierrez P.

Abimael Gutierrez P.
Founder of apdesc