Como crear una Redirección 301
Redirección 301 con ASP Clásico
<%@ Language=VBScript %>
<%
Response.Status=»301 Moved Permanently»
Response.AddHeader «Location»,»http://www.new-url.com/»
%>
Redirección 301 con ASP .NET
<script runat=»server»>
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = «301 Moved Permanently»;
Response.AddHeader(«Location»,»http://www.new-url.com»);
}
</script>
Redirección 301 con JSP (Java)
<%
response.setStatus(301);
response.setHeader( «Location», «http://www.new-url.com/» );
response.setHeader( «Connection», «close» );
%>
Redireccion 301 usando CGI PERL
$q = new CGI;
print $q->redirect(«http://www.new-url.com/»);
Redirección 301 usando Ruby on Rails
def old_action
headers[«Status»] = «301 Moved Permanently»
redirect_to «http://www.new-url.com/»
end
Redireccion usando htaccess
Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
Atención: este método solo trabaja en servidores Linux que tengan Apache corriendo el Mod-Rewrite
Redirección de www y sin www al mismo dominio usando htaccess
Options +FollowSymlinks
RewriteEngine on
rewritecond %{http_host} ^domain.com [nc]
rewriterule ^(.*)$ http://www.domain.com/$1 [r=301,nc]
Atención: este método solo trabaja en servidores Linux que tengan Apache corriendo el Mod-Rewrite
Seguridad para Apache mediante HTACCESS
Del mismo modo debes tener en cuenta que algunas de estas recomendaciones pueden disminuir el rendimiento de tu servidor dependiendo de tu configuración y de las especificaciones del sistema.
Primero, cerciorate de tener instalado los últimos parches de seguridad
No tiene sentido poner una cerradura mas resistente a tu puerta si dejas la ventana abierta.Del mismo modo si no tenemos los ultimos parches de seguridad instalado no tendría sentido continuar con la optimización de seguridad.
Restringir acceso por IP
Si tienes un recurso al que deba solamente tener acceso alguna red, o IP en concreto puedes configurarlo en Apache. Por ejemplo si deseas restringir el acceso a tu Intranet para permitir solamente la red 176.16:
Order Deny,Allow
Deny from all
Allow from 176.16.0.0/16
o por IP:
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Oculta la versión y otra información delicada
Por defecto muchas instalaciones de Apache muestran el número de versión que está funcionando, el sistema operativo y un informe de módulos de Apache están instalados en el servidor. Los usuario maliciosos pueden utilizar esta información para atacar tu servidor.
Hay dos directivas que necesitas agregar, o corregir en tu archivo de httpd.conf:
ServerSignature Off
ServerTokens Prod
El ServerSignature aparece en la parte inferior de las páginas generadas por apache tales como los famosos errores 404.
La directiva ServerTokens se utiliza para determinarse lo que pondrá Apache en la cabecera de la respuesta HTTP del servidor.
Apache debe funcionar bajo su propia cuenta y grupo de usuario
Algunas versiones de Apache corren bajo el usuario nobody, esto compromete mucho su seguridad por lo tanto haz lo siguiente:
User apache
Group apache
Utiliza el mod_security
El mod_security es un módulo estupendo de Apache escrito por Ivan Ristic, el autor de Apache Security de O’Reilly.
Esta es una lista de cosas que puedes hacer con mod_security:
* Filtración simple
* Filtración basada en expresiónes regular
* Validación de codificación de la URL
* Validación de codificación Unicode
* Auditing
* Prevención del ataque NULL Byte
* Límitar la memoria de subida
* Enmascarar la identidad del servidor
* Y más
Deshabilitar cualquier módulo innecesario
Apache viene por defecto instalado con un serie de módulos.Debes echarle un vistazo a la documentación de Apache y ver para que sirve cada uno de ellos, y de esta manera te darás cuenta de que hay algunos que no son útiles en tu servidor.
Busca en httpd.conf las lineas que contengan LoadModule. Para deshabilitar el módulo debes agregar un # al principio de la línea, para que de esta forma pase a ser un comentario. Para buscar los módulos prueba con:
grep LoadModule httpd.conf
Aquí están algunos módulos que se instalan por defecto pero a menudo no son necesarios: mod_imap, mod_include, mod_info, mod_userdir, mod_status, mod_cgi, mod_autoindex.
Asegurarte de que los archivos a los que se accede son los deseados
No deseamos que se pueda acceder a los directorios que no tengan permisos para ello, supongamos que el directorio raiz para nuestras webs es /web, la configuración óptima debera ser la siguiente:
Order Deny,Allow
Deny from all
Options None
AllowOverride None
Order Allow,Deny
Allow from all
Desactiva las opciones para explorar directorios
Esto lo puedes hacer con las opciones de directiva dentro de la etiqueta directorio tiene dos posibles valores none o indexes.
Options -Indexes
Desactiva los includes del lado servidor
Esto también se hace con las opciones de directiva dentro de la etiqueta directorio tiene dos posibles valores none o include.
Options -Includes
Desactiva la ejecución de CGI
Si no necesitas la ejecución de CGI por algún motivo en concreto desacrivalos se hace con las opciones de directiva dentro de la etiqueta directorio tiene dos posibles valores none o ExecCGI.
Options -ExecCGI
No permitir que apache siga enlaces simbólicos
De nuevo se configura con las opciones de directiva dentro de la etiqueta directorio tiene dos posibles valores none o FollowSymLinks.
Options -FollowSymLinks
Desactivar todas las opciones
Si deseas desactivar el uso de todas las opciones simplemente:
Options None
Si solamente deseas desactivar algunas en concreto, separalas con un espacio en las opciones de directiva:
Options -ExecCGI -FollowSymLinks -Indexes
Desactivar la ayuda para los archivos .htaccess
Esto esta ya hecho pero con la directiva AllowOverride. Cámbialo a none.
AllowOverride None
Otra opción interesante sería bloquear la descarga de todos los archivos que comienzen con .ht por ejemplo, se haría de la siguiente manera:
AccessFileName .httpdoverride
Order allow,deny
Deny from all
Satisfy All
Disminuye el valor máximo de tiempo de espera
Por el defecto el tiempo de espera es de 300 segundos. Puedes disminuirlo por seguridad para prevenir ataques de esta manera:
Timeout 45
Limitar el tamaño maximo de peticiones
Apache tiene varias directivas que permiten que limites el tamaño de una petición, esto puede ser muy útil.
Una buena manera de comenzar es con la directiva LimitRequestBody. Esta directiva esta fijada a ilimitado por defecto. Si estás permitiendo uploads de archivos que no sean mayores a 1MB, podrías fijar este ajuste a algo parecido a esto:
LimitRequestBody 1048576
Si no estás permitiendo uploads de archivos puedes fijarlo incluso a un tamaño más pequeño.
Algunos otras directivas a mirar son LimitRequestFields, LimitRequestFieldSize y LimitRequestLine.
Conclusión
Espero que estas recomendaciones os hayan sido útiles y recuerda que el uso que le tienes que dar depende en gran medida de los recursos que necesitas y de las caracteristicas de tu servidor, antes de hacer cualquier cambio si no estas seguro documéntate y utiliza este artículo unicamente como una referencía que te lleve a la solución más idonea.
Fuente en ingles: www.petefreitag.com
Fuente en español: tufuncion.com
Duplicate content fix index.html vs / (slash only)
This similar to the www vs non-www version of your site work-around.
As you might now you, by default you can access your site as http://www.domain.com/ and http://www.domain.com/index.html with some setups it can be index.php or index.asp or default.aps, etc.
Unfortunately, this creates a risk of duplicate content from the search engine point of view. To avoid this, you can use the following ModRewrite rules in your .htaccess file:
RewriteEngine on RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.html\ HTTP/ RewriteRule ^index\.html$ http://www.domain.com/ [R=301,L]
The file should be located in your website main folder (web root).
The rules above will tell the browser or the search engine both that all requests to index.html should be directed to the «/» (slash only).
Force www vs non-www to avoid duplicate content on Google
Recently, it has been talked a lot about Google and duplicate content as well as Google Canonical problems.That is, when you have your site accessible both under your_domain.com and www.your_domain.com. To avoid such problems you can use the following lines in your .htaccess file to force only the www version of your web site:
RewriteEngine on RewriteCond %{HTTP_HOST} !^www.your_domain.com$ RewriteRule ^(.*)$ http://www.your_domain.com/\ [R=301]
Please, note that the .htaccess should be located in the web site main folder.
This will redirect all requests to the non-www version of your site to the www version using 301 Permanent redirect which will make the search engines to index your site only using the www.your_domain.com URL. In this way you will avoid a duplicate content penalty.
HTTP Authentication with PHP running as CGI/SuExec
Here it is a tricky one. PHP is a feature-rich programming language and they even have a simple HTTP Auhtentication included.
The bad news is that this type of Authorization does not work when your PHP is installed and working as CGI. It works perfectly when PHP is installed as a module though.
However, there is a workaround available which can make HTTP Auth for PHP working even when in CGI mode.
First you need to create the following .htaccess file:
RewriteEngine on
RewriteRule .* – [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>
The lines above will assign the username/pass pairs to an environment variable named HTTP_AUTHORIZATION.
Then in your PHP script you should add the following, right before your user/pass check routine:
So here it is how a sample PHP script using HTTP Authentication would look like:
<?php
// split the user/pass parts
list($_SERVER[‘PHP_AUTH_USER’], $_SERVER[‘PHP_AUTH_PW’]) = explode(‘:’, base64_decode(substr($_SERVER[‘HTTP_AUTHORIZATION’], 6)));
// open a user/pass prompt
if (!isset($_SERVER[‘PHP_AUTH_USER’])) {
header(‘WWW-Authenticate: Basic realm=»My Realm»‘);
header(‘HTTP/1.0 401 Unauthorized’);
echo ‘Text to send if user hits Cancel button’;
exit;
} else {
echo «<p>Hello, </p>».$_SERVER[‘PHP_AUTH_USER’];
echo «<p>You entered as your password: </p>».$_SERVER[‘PHP_AUTH_PW’];
}
?>
Change PHP variables using .htaccess
If you need to change the way your PHP is working you can do that using .htaccess.
Please, note that not all PHP options can be changed using .htaccess.
A list of options that can be changed using .htaccess file can be found at:
http://www.php.net/manual/en/ini.php#ini.list
The ones that can be changed with .htaccess are the ones marked with: PHP_INI_PERDIR or PHP_INI_ALL. The ones marked as PHP_INI_SYSTEM cannot be changed via .htaccess files.
The syntax is pretty simple:
php_flag [variable_name] [value]
For example if you need to turn off register_globals:
php_flag register_globals off
If you need to change the PHP include path:
php_value include_path ".:/usr/local/lib/php:/your_include/path"
The include_path string starts with a dot “.” And then each additional path is separated with a semi colon. (e.g. .:/path1:/path2:/path3)
Make PHP to work in your HTML files with .htacess
By default most web servers across the internet are configured to treat as PHP files only files that end with .php. In case you need to have your HTML files parsed as PHP (e.g .html) or even if you want to take it further and make your PHP files look like ASP, you can do the following:
For web servers using PHP as apache module:
AddType application/x-httpd-php .html .htm
For web servers running PHP as CGI:
AddHandler application/x-httpd-php .html .htm
In case you wish to do the ASP mimick:
For PHP as module:
AddType application/x-httpd-php .asp
OR
For PHP as CGI:
AddHandler application/x-httpd-php .asp
How to add Mime-Types using .htaccess
In case your web hosting account is not configured to server certain mime types with the proper content type. You can change this using .htaccess file.
For example if you need to configure your server to display ASX files:
AddType video/x-ms-asf asf asx
For windows media audio WMA
AddType audio/x-ms-wma .wma
A comprehensive list of mime-types can be found here
There is one more useful feature of the AddType directive. Most of you most probably know that Internet Explorer opens MS Word, Excell, PDF and some other files inside a browser window. To force the browser to download the file you can use AddType to change the document type:
AddType application/octet-stream .doc .xls .pdf
Introduction to mod_rewrite and some basic examples
ModRewrite is a powerful feature of the Apache web server. It provides an easy way to modify/manipulate URLs. As complicated as it sounds a regular webmaster can benefit from this feature in many way. I will list here the ones I consider most useful for the regular webmaster.
Create easy to remember URLs or also known as COOL URIs, other call them Search Engine Friendly URLs. For example you have some complicated site driven by some server-side scripting language: PHP, Perl, etc. In general its URLs will look like
It is not easy to remember such URL.
Using ModRewrite you can make the URL look like:
Here is the code:
RewriteRule ^([a-z]*)/([a-z]*)/([1-9]+)(-[1-9]+)? $ http://www.example.com/view.php?cat=$2&a=$3&page=$4&lang=$1 [L]
What the code does? It tries to match the requested URL against a regular expression string.
In case it finds a match it performs an internal rewrite. The user will never see the long URL in his browser.
Change enviromental variables
An example can be found here
The official ModRewrite documentation can be found at:
http://httpd.apache.org/docs/1.3/misc/rewriteguide.html
In the next several articles you will find some commonly used ModRewrite rules for performing everyday tasks.
Change default directory page
Most probably you have been wondering how the Webserver decides which page from your site to use as a main/default page of your site. There is a directive named DirectoryIndex which takes care of this.
On most web servers there is a pre-defined set of file names which server a start page.
The most commonly used are: index.html, default.html, index.php, index.asp, etc.
The good news is that you can set your custom file to be a start page of your site using .htaccess.
For example the following line set home-page.html as a main page of your site:
DirectoryIndex home-page.html
The DirectoryIndex directive can accept more than one name:
DirectoryIndex home-page.html Home.html, index.html index.php index.cgi
So when a visitors goes to http://www.example.com the first page to be loaded will be the home-page.html if it cannot be found the server will look then for Home.html, index.html, etc until it finds a match.