Search code examples
apache.htaccessmod-rewrite

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


The URLs are:

  • (Doesn't work) http://example.com/seller/samsung
  • (Works) http://example.com/seller/samsung/

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?


Solution

  • 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.