• Navega al azar. Pulsa las flechas y deja que la fortuna te dispense un artículo.

    lunes, 9 de febrero de 2015

    htaccess de un vistazo

    Cuando te dedicas a hacer páginas web en un hosting propio tarde o temprano tienes que plantearte tocar el archivo .htaccess. Y una y otra vez tienes que andar buscando por Internet lo que necesitas. A mi me pasa constantemente así que me voy a montar la chuleta aquí para cuando me haga falta. Y de paso, queda también para el resto del mundo.

    Sustituye tuSITIO por el tuyo, cambiando el .com por la extensión que sea.

    REWRITE Y REDIRECCIONES

    - Para forzar que la URL siempre tenga www.

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


    - Para forzar que la URL siempre tenga www. (sin citar el dominio)

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


    - Para forzar que la URL no tenga www.

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


    - Para forzar HTTPS

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


    - Para forzar la barra inclinada final (/)

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


    - Redirige a una página determinada (2 ejemplos)

    Redirect 301 /antiguapagina.html http://www.tuSITIO.com/nuevapagina.html
    Redirect 301 /antiguapagina2.html http://www.tuSITIO.com/carpeta/


    - Redirige un sitio entero (mantiene los enlaces internos sin cambios)

    Redirect 301 / http://newsite.com/



    SEGURIDAD

    - Denegar acceso a todos

    Deny from All


    - Denegar acceso a todos excepto a ti
    Ojo, esto funciona usando tu IP, aquí mostrada como xxx.xxx.xxx.xxx. Si cambia tu IP tampoco tendrás acceso y tendrás que cambiar el htaccess.

    Order deny, allow
    Deny from All
    Allow from xxx.xxx.xxx.xxx


    - Permitir a todos excepto a spammers y trolls
    Hay que añadir las IPs de aquellos a quienes deseas prohibir la entrada. Funciona relativamente ya que también pueden cambiar de IP pero puede ser útil.

    Order deny, allow
    Allow from All
    Deny from xxx.xxx.xxx.xxx
    Deny from xxx.xxx.xxx.xxy

    - Denegar acceso a archivos ocultos y directorios

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

    - Denegar acceso a backups y archivos con código fuente


    <FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
    Order allow,deny
    Deny from all
    Satisfy All
    </FilesMatch>

    - Deshabilitar navegación en directorios

    Options All -Indexes

    - Deshabilitar hotlinking a imágenes (que no puedan enlazar directamente a una imagen)

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

    - Proteger con contraseña (password) un directorio

    Primero tienes que crear un archivo .htpasswd escribiendo en él el nombre de usuario y la contraseña, así:

    nombreusuario:contraseña

    Puedes, si quieres, codificar la contraseña (elige base64)

    Lo subes al directorio que quieres proteger y luego agrega allí un .htaccess con lo siguiente (indicando la ruta correcta al .htpasswd. En este ejemplo: /home/privado/.htpasswd)

    AuthType Basic
    AuthName "Area restringida"
    AuthUserFile /home/privado/.htpasswd
    Require valid-user


    RENDIMIENTO

    - Comprimir archivos de texto

    <IfModule mod_deflate.c>
    <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
    SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
    RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
    </IfModule>
    <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>

    - Configurar Expires Headers
    Le dice a los navegadores cuando deben descargar determinados archivos del servidor en vez de usar los que tenga almacenados en su propia caché por visitar el sitio anteriormente.

    <IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault "access plus 1 month"
    # CSS
    ExpiresByType text/css "access plus 1 year"
    # Intercambio de datos
    ExpiresByType application/json "access plus 0 seconds"
    ExpiresByType application/xml "access plus 0 seconds"
    ExpiresByType text/xml "access plus 0 seconds"
    # Favicon
    ExpiresByType image/x-icon "access plus 1 week"
    # Componentes HTML
    ExpiresByType text/x-component "access plus 1 month"
    # HTML
    ExpiresByType text/html "access plus 0 seconds"
    # JavaScript
    ExpiresByType application/javascript "access plus 1 year"
    # Archivos Manifest
    ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
    ExpiresByType text/cache-manifest "access plus 0 seconds"
    # Media
    ExpiresByType audio/ogg "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType video/mp4 "access plus 1 month"
    ExpiresByType video/ogg "access plus 1 month"
    ExpiresByType video/webm "access plus 1 month"
    # Feeds
    ExpiresByType application/atom+xml "access plus 1 hour"
    ExpiresByType application/rss+xml "access plus 1 hour"
    # Fuentes
    ExpiresByType application/font-woff "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
    ExpiresByType application/x-font-ttf "access plus 1 month"
    ExpiresByType font/opentype "access plus 1 month"
    ExpiresByType image/svg+xml "access plus 1 month"
    </IfModule>
    - Deshabilitar eTags
    Impide al navegador validar archivos forzándolo a utilizar los Expire Headers configurados en el punto anterior. Comprueba si sucede algún error y, en ese caso, no utilices esto.

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

    OTRAS

    - Configurar variables PHP
    Esto puede hacerse también en el archivo php.ini pero si no se tiene acceso a él lo especificamos en el .htaccess. Esto son solo dos ejemplos:

    php_value upload_max_filesize 50M
    php_value max_execution_time 240

    - Páginas de error personalizadas
    En vez de usar las que tiene por defecto el servidor puedes hacer tus propias páginas de error y nombrarlas como quieras.

    ErrorDocument 400 /errors/algofuemal.html
    ErrorDocument 401 /errors/prohibidoelpaso.html
    ErrorDocument 403 /errors/peligro.html
    ErrorDocument 404 /errors/perdidos.html
    ErrorDocument 500 /errors/servidormalito.html

    - Permitir fuentes de otros dominios.
    Las fuentes web de otros dominios o de un CDN pueden no funcionar en Firefox o IE. Esto podría solucionarlo.

    <IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff)$">
    Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
    </IfModule>
    
    - Codificación UTF-8 automática

    # Usar codificación UTF-8 para cualquier text/plain o text/html
    AddDefaultCharset utf-8

    # Fuerza UTF-8 para determinados formatos de archivo
    AddCharset utf-8 .atom .css .js .json .rss .vtt .xml

    - Forzar la descarga
    A lo mejor te interesa que determinados ficheros se descarguen en vez de mostrarse en el navegador. Simplemente cambia la extensión o extensiones.

    <Files *.avi>
    ForceType application/octet-stream
    Header set Content-Disposition attachment
    </Files>
    
    Otra forma:
    <FilesMatch "\.(jpg|zip|avi)$" >
    ForceType application/octet-stream
    Header add Content-Disposition "attachment" </FilesMatch>


    También te puede interesar:

    - .HTACCESS PERFECTO: configura y genera automáticamente el .htaccess que necesites.

    - .HTACCESS URL REWRITE: generador automático de redirecciones para htaccess.




    No hay comentarios:

    Publicar un comentario

    El Plus

    Conexiones



    El Twitter