简体   繁体   中英

How to remove extension from url WITHOUT trailing slash using .htaccess?

I have a .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

And I have a file called random.php .

All I want to do is just call something.com/random , but Apache adds a trailing slash (using 301 Redirect) to the end of the URL, therefore giving an error stating that something.com/random/.php cannot be found.

EDIT 1: When I use

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [NC,L]

then my external files (.js, .css, etc.) can't load and the server responds with a 500 Internal Server Error response. Apache says that there were too many redirects.

Try this rule with optional trailing slash:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f    
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

You almost had it right, you just needed to exclude the slash as well:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.\/]+)$ $1.php [NC,L]    

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