简体   繁体   中英

RewriteRule htaccess to always remove trailing slash even directory

The target is to combine several rules:

  • never have a trailing slash in the URI
  • internally rewrite to the index.php (domain.tld/somedir/index.php) when calling domain.tld/somedir
  • remove file extensions , check if + '.php' exists and eventually internally rewrite to it

This is to be done in '.htaccess' as this is my only accessible .

My attempt so far

# check if *.php exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*[^/])/?$ $1.php [L, QSA]

# do not allow trailing slash
RewriteRule (.*)/ $1 [L, R=301]

The difficulty here is that the query 'domain.tld/somedir' normally calls the directory's index.php after having been redirected to 'domain.tld/somedir/'. However, I would like the index.php to be internally called (no 301) directly when querying 'domain.tld/somedir'.

You can use this code:

DirectoryIndex index.php
RewriteEngine On

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ /$1 [R=301,L]

# To internally forward /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f [NC]
RewriteRule ^(.+?)/?$ /$1.php [L]

There is a separate setting in apache called DirectorySlash that can be enabled/disabled. You can read more at httpd.apache.org/docs/2.2/mod/mod_dir.html#directoryslash but be sure to read the part about why this is done right below where it says "some good reasons". Also note the security issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM