skip to Main Content

I am trying to get apache to redirect every URL to add a trailing slash to the end. I’m having an issue with the following type of URL.

http://mywebsite.com/profile/david.tate

The rule I have doesn’t add a trailing slash to the end of this type of URL for whatever reason. I need to add the slash to the end.

I’ve searched stackoverflow for some answers but I can’t find anything that can help. I’m not an expert with URL rewrites.

Here’s the rule I have right now.

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

Can you please tell me how I can write the URL above to have a trailing slash on the end?

Thank you

2

Answers


  1. I assume you only want to redirect requests to URLs with a period in the last part of the path? And probably also only if it resembles something like the old “file name extension” separated by a period from the base name of a file. So that something precedes the period and something actually follows the period in the “file name”?

    RewriteEngine on
    RewriteRule [^/]+.[^/]+$ %{REQUEST_URI}/ [R=301]
    

    You need to take care that there is no other rule in place somewhere that removes that trailing slash again, that is often the case in frameworks and the like to keep URLs pretty…

    It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out…

    This rule will work likewise in the http servers host configuration or inside a dynamic configuration file (“.htaccess” file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a dynamic configuration file you need to take care that it’s interpretation is enabled at all in the host configuration and that it is located in the host’s DOCUMENT_ROOT folder.

    And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (“.htaccess”). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

    Login or Signup to reply.
  2. You can use this rule to add a trailing slash to all URLs except for existing files:

    RewriteEngine On
    
    # add a trailing slash to directories
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search