0

I am new to .htaccess. I want to redirect url ending without slash to one with a slash like the code below:

Redirect www.mydomain.com/page1 www.mydomain.com/page1/ 

This doesn't work. What am I doing wrong?

Sanu0786
  • 571
  • 10
  • 15
Roman
  • 1,118
  • 3
  • 15
  • 37

2 Answers2

1

To enforce a trailing-slash policy:

<IfModule mod_rewrite.c>
     RewriteCond %{REQUEST_URI} /+[^\.]+$
     RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [L,R] # <- for test, for prod use [L,R=301]
</IfModule>

EDIT: commented the R=301 parts because, as explained in a comment:

Be careful with that R=301! Having it there makes many browsers cache the .htaccess-file indefinitely: It somehow becomes irreversible if you can't clear the browser-cache on all machines that opened it. When testing, better go with simple R or R=302

After you've completed your tests, you can use R=301. You can try this. Copy the following in your htaccess file to add a trailing slash to your website.

localroot
  • 566
  • 3
  • 13
1

You don't use the domain in the Redirect, only the path

Redirect /page1 /page1/

This will only work on defined paths. If you need a more general approach, use RewriteRule from the mod_rewrite module with a regular expression

RewriteRule ^(.*[^/])$ /$1/ [R=302,L,QSA]

This will check for any string that does not end with a / and append the slash in the 302 Redirect. That's pretty much information going on in just on short line of code.

Edit/Remark

I'm using 302 Redirect here. This may lead to Google penalties by duplicate content. In that case a 301 redirect is necessary. Since there is no standard regarding whether a redirect should be cached and how long and if a redirect loop should result in an overwrite (having issues in Brave Browser with the latter one), I recommend to set the Caching policy to no cache for any redirect. One can do it by setting an environment variable when the Rewrite applies and settings the Cache headers, if this environment variable is set:

# Add `nocache` environment variable if rewrite
RewriteRule ^(.*[^/])$ /$1/ [R=302,L,QSA,E=nocache:1]

<IfModule mod_headers.c>
  ## Set the response header if the "nocache" environment variable is set
  ## in the RewriteRule above.
  Header always set Cache-Control "no-store, no-cache, must-revalidate" env=nocache

  ## Set Expires too ...
  Header always set Expires "Thu, 01 Jan 1970 00:00:00 GMT" env=nocache
</IfModule>
yunzen
  • 32,854
  • 11
  • 73
  • 106
  • 1
    @Roman you must have some other config that causes that. This RewriteRule cannot yield your false result. See here: https://htaccess.madewithlove.be?share=50961f69-56c4-5df0-93d0-13782a3f4c8d – yunzen Nov 19 '18 at 09:37
  • do you have any idea what can be in conflict? https://stackoverflow.com/questions/53372978/code-in-my-htaccess-causing-too-many-redirects – Roman Nov 19 '18 at 11:08