skip to Main Content

On my website, I only use 3 slashes in my URL path:

https://example.com/this/isatest/

Right now I use .htaccess which makes it possible (as a side effect) to add as many stuff on the URL as you like:

https://example.com/this/isatest/hipperdihopperdus/pizza/bacon/with/cheese

I’d like to automatically remove everything after “isatest” while keeping the trailing slash using .htaccess.

This is what my .htaccess currently looks like:

Options -Indexes
Options +FollowSymLinks
RewriteEngine on

# 301 Redirect all requests that don't contain a dot or trailing slash to
# include a trailing slash
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_URI} !.
RewriteRule ^(.*) %{REQUEST_URI}/ [R=301,L]

RewriteCond %{THE_REQUEST} /index.html [NC]
RewriteRule ^index.html$ /? [R=301,L,NC]

RewriteRule ^listen/$ /console/ [NC,L]

# Rewrites urls in the form of /parent/child/
# but only rewrites if the requested URL is not a file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?page=$1 [L,QSA]

How can I achieve this?

2

Answers


  1. As your first rule, after the RewriteEngine directive, you can do something like the following:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]
    

    This checks if there is anything else (the dot) after two path segments and a slash, and redirects to removed “anything else”.

    Note that this is a 302 (temporary) redirect. Only change this to a 301 (permanent) redirect – if that is the intention – once you have confirmed that it works OK. This is to avoid the browser caching erroneous redirects whilst testing.

    UPDATE: It may be more efficient to simply avoid redirecting files that end in a recognised file extension. Or perhaps exclude known directory location(s) of your static resources. For example:

    RewriteCond %{REQUEST_URI} !.(css|js|jpg|png|gif)$ [NC]
    RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]
    

    OR,

    RewriteCond %{REQUEST_URI} !^/static-resources/
    RewriteRule ^([^/]+/[^/]+/). /$1 [R=302,L]
    
    Login or Signup to reply.
  2. You can add this rule just below RewriteEngine On line:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+/[^/]+/).+$ /$1 [R=301,L,NE]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search