Following the recommendations of Google on redirección 301
which it indicates in its articles that it can happen that the pages are available both with a slash / slash at the end (/)
and without it. For example:
http://www.example.com/pagina
http://www.example.com/pagina/
If so, in this case it is a duplicity that can only be resolved by redirecting one version to the other.
Now my question?
- How to redirect all pages without slash/slash to version with trailing slash/slash?
I tried adapting this code to my file .htaccess
but there were problems adapting it.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule (.*) http://www.example.com/$1/ [R=301,L,QSA]
Important: In my file ,
.htaccess
the URLs work both ways without problems, both with a slash/slash at the end(/)
and without it.
My .htaccess file
# Activamos mod_rewrite
RewriteEngine on
# Seleccionamos el directorio base para el RewriteRule
RewriteBase /project/
# Aquí nos evitamos comprobar que sea un archivo (agrego comprobación
# para detectar también directorio) en cada conjunto de reglas
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ $1 [QSA,L]
# Obtenemos todo lo que vaya tras "assets/" y subdirectorios previstos
RewriteCond %{REQUEST_URI} assets/(css|fonts|js|img)/(.+)$
# Entonces (si se cumplen todas las condiciones) redirigimos (R)
# y dejamos de evaluar el resto de reglas (L)
RewriteRule ^(.*)$ assets/%1/%2 [L,R]
# Tu/s regla/s
RewriteRule ^online-video-en-hd-gratis/?$ video.php [L,NC,QSA]
RewriteRule ^online/video/hd/free/?$ online.php [L,NC,QSA]
On the other hand I do not know if it is correct to allow or not to enter the specific URL example:
example.com/online.php
or redirect to the personalized URLexample.com/online/video/hd/free/
The regular expression
^(.*[^/]$)
matches any URL where the last character is not a/
. At the same time, it captures all the text in$1
.To that, we add a condition before, to check that a file with that name does not exist. Thus, we guarantee that the trailing slash is only added if you are not trying to access a file (file, not folders):
In your particular case, I think we should do it the other way around: if the file exists, no more rules are checked; and if it does not exist, continue with the rest. He
.htaccess
would look like this:Tests:
I uploaded it to a free hosting, where you can try the addresses:
http://mariano.freevar.com/43005/proof/
![Access /test/ with 200 OK](https://i.stack.imgur.com/A4H3P.png)
which directly accesses the resource
http://mariano.freevar.com/43005/tests
![Get a 301 Moved Permanently on /test and access /test/ with 200 OK](https://i.stack.imgur.com/qqaUO.png)
that it gets a 301 and redirects to the URL with
/
at the end that it accessestry this rule: