Is the below .htaccess code correct? It is used for SEO purposes. I found it in google but I want to be sure it is okay to use. It is placed in .htaccess file and used to force a slash on non-slash URLs. Also, specifically, is the /$1/$2/ part correct?
#Force Trailing Slash
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.domain.com/$1/$2/ [L,R=301]
Will I need to also include a RewriteRule for the non-www url (see below) ?
RewriteRule ^(.*)$ http://domain.com/$1/$2/ [L,R=301]
Also, is it true that you only need to have the below ONCE at the very top of .htaccess?
RewriteEngine On
RewriteBase /
Also, how do you TEST if this code is indeed working? I put the code in my .htaccess file but my homepage does not display a trailing slash.
Edit: Follow-up Question:
Figure A
RewriteRule ^(.*)$ http://www.domain.com/$1/
Does "Figure A" Rewrite Rule only force a trailing slash for
http://www.domain.com/post-one
Will "Figure A" RewriteRule also force a trailing slash for
http://www.domain.com/category/post-one
If not, how do you add a grouping so that you can do the /$1/$2/ thing?
Would you suggest doing the /$1/$2/ thing (for SEO purposes)? Is there any harm to doing this?
specifically, is the /$1/$2/ part correct?
No, youre going to get redirected to have 2 trailing slashes because $2
doesn't backreference anything. $1
backreferences the (.*)
but you don't have a second grouping. You just need:
RewriteRule ^(.*)$ /$1/ [L,R=301]
Will I need to also include a RewriteRule for the non-www url (see below) ?
No, the 2nd parameter for the RewriteRule
directive is the target, so unless you want to redirect people to domain.com
instead of www.domain.com
you don't need to add anything.
Also, is it true that you only need to have the below ONCE at the very top of .htaccess?
Yes
TO test, just add your htaccess file and go to a URL without a trailing slash. The browser should get redirected and you'll see in the location bar the same URL but with a trailing slash. If that's not what you see, something else is wrong.