Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force some pages to end in a slash [.htaccess]

Tags:

.htaccess

This is a multi-site problem. I have a lot of sites with .htaccess files with multiple line similar to:

rewriterule ^(page-one|page-two|page-three)/?$ /index.php?page=$1 [L]

This means that both www.domain.com/page-one and www.domain.com/page-one/ will both load www.domain.com/index.php?page=page-one

However I'm always told that it is good SEO practice to make sure you use only one URL per page so what I'd like to do make www.domain.com/page-one to redirect to www.domain.com/page-one/ via the .htaccess file.

Please note the answer I'm NOT looking for is to remove the ?$ from the end of the line as that will just cause www.domain.com/page-one to become a 404 link.

like image 527
Andrew G. Johnson Avatar asked Nov 27 '08 18:11

Andrew G. Johnson


People also ask

How do you add a trailing slash in htaccess?

How to add a trailing slash to URLs. One of the easiest and most convenient way to add or enforce trailing slashes on URLs is by RewriteRule directive. You can write a single rule in your htaccess file that will apply to all URLs without a trailing slash.

How do I force trailing slash in WordPress?

To do so, go to the “Settings -> Permalinks” section and, depending on your situation, either add or delete the last slash. The “Custom Structure” field ends with a slash, so all other WordPress URLs will have the trailing slash. Likewise, if it is not present there, the slash will be missing in your website's URLs.

What is a trailing slash in URL?

Email Subscription. A trailing slash is a forward slash (“/”) placed at the end of a URL such as domain.com/ or domain.com/page/. The trailing slash is generally used to distinguish a directory which has the trailing slash from a file that does not have the trailing slash.

How do you remove the slash at the end of a URL?

Use the String. replace() method to remove a trailing slash from a string, e.g. str. replace(/\/+$/, '') .


1 Answers

Here's a snippet to force everything to end with a slash

rewritecond %{REQUEST_FILENAME} !-f
rewritecond %{REQUEST_URI} !(.*)/$
rewriterule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]
like image 197
Andrew G. Johnson Avatar answered Oct 13 '22 10:10

Andrew G. Johnson