skip to Main Content

I’ve searched stackoverflow and numerous websites for an answer to this. So please don’t shoot me if it’s already been answered on stackoverflow. I am stuck.

I want to Add Slash to a particular url.

www.example.com/ppc/photo/sd-xxx to 
www.example.com/ppc/photo/sd-xxx/

But I am already using remove slash htaccess code in my htaccess Code

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

I want to Add Slash on Particular folder urls only, reason they are already added on Adsense, So we don’t want to Change that url.

2

Answers


  1. You can either add a specific .htaccess in that folder or add <directory> directive to your main .htaccess, with the rule you need

    Login or Signup to reply.
  2. You can do something like the following near the top of the root .htaccess file:

    # Identify specific URLs to which a trailing slash should be added
    RewriteCond %{REQUEST_URI} ^/ppc/photo/sd-xxx [OR]
    RewriteCond %{REQUEST_URI} ^/ppc/photo/another
    RewriteRule ^ - [E=ADD_TRAILING_SLASH:YES]
    
    # Add slash to specific URLs
    RewriteCond %{ENV:ADD_TRAILING_SLASH} =YES
    RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]
    
    # Remove slash on other URLs
    RewriteCond %{ENV:ADD_TRAILING_SLASH} !=YES
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.+)/$ /$1 [R=301,L]
    

    The first rule sets an environment variable if one of the URLs is requested that should have a trailing slash appended.

    The second rule then adds the trailing slash to one of those URLs, if it has been omitted.

    The third rule removes the trailing slash on other URLs. This is similar to your original rule, with an additional condition that prevents the rule from being processed when one of your special URLs are requested. I also removed the unnecessary condition that tests for the trailing slash and captures the URL-path before the trailing slash and moved this to the RewriteRule pattern – this is fine providing the .htaccess file is in the document root.

    You will need to clear your browser cache before testing. Since the earlier 301 (permanent) redirect that removed the trailing slash from these URLs will have been cached by the browser. Test first with a 302 (temporary) redirect to avoid potential caching issues.


    HOWEVER, this could be simplified if the "particular folder URL(s)" follow a simple pattern that can be summarised with a single regex. eg. URLs of the form /ppc/photo/sd-xxx, where xxx is any 3 letters/digits (as your example perhaps alludes to). The above could then be reduced to the following:

    # Add slash to specific URLs
    RewriteRule ^ppc/photo/sd-w{3}$ /$0/ [R=301,L]
    
    # Remove slash on other URLs
    RewriteCond %{REQUEST_URI} !^/ppc/photo/sd-w{3}/$
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.+)/$ /$1 [R=301,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search