Carl
Carl

Reputation: 817

No trailing slash causes 404, how to fix using htaccess?

The URLs are:

The .htaccess rule I have for these types of URLs looks like:

RewriteRule ^seller/[^/]+/(.*)$ ./$1

What can I do to make both of these URLs to go to the same page?

Upvotes: 2

Views: 1934

Answers (2)

Viraj Nevase
Viraj Nevase

Reputation: 1

Place this code in your .htaccess file in the root directory of your website.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*[^/])$ %{REQUEST_URI}/ [L,R=301]

RewriteEngine On: Enables the Apache mod_rewrite module for URL rewriting.

RewriteCond %{REQUEST_FILENAME} !-f: This condition checks if the requested URL does not map to an existing file.

RewriteCond %{REQUEST_URI} !(.*)/$: This condition checks if the requested URL does not already have a trailing slash.

RewriteRule ^(.*[^/])$ %{REQUEST_URI}/ [L,R=301]: This rule captures URLs without a trailing slash and redirects them to the same URL with a trailing slash using a 301 (permanent) redirect. The [L] flag stops further processing, and the [R=301] flag indicates a permanent redirect.

This rule ensures that whenever a user accesses a URL without a trailing slash, they will be redirected to the same URL with a trailing slash, eliminating the 404 error.

Remember to test this on a development/staging environment before deploying it to your live website to ensure it works as expected. Also, ensure you have the mod_rewrite module enabled on your Apache server for this to work.

Upvotes: 0

Joe
Joe

Reputation: 4897

You could just force a trailing slash to appear on the end of your URLs. You can do that by using the following in your .htaccess:

RewriteCond %{REQUEST_URI} !(/$|\.) 
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]

Just make sure you clear your cache before you test this.

EDIT:

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

What does the above do? So the condition grabs your directory, so for example /samsung and will check if it has a / on the end. If it does not, it will grab the directory at the end of URL (once again /samsung and add a / on to it. It will do this using a 301 redirect and would leave you with /samsung/.

As for the L flag (taken from official documentation):

The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.

Upvotes: 3

Related Questions