简体   繁体   中英

.htaccess remove PHP extension conflicts with redirect trailing slash

I have three pieces of code.

Here's the first one:

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

The second one:

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R,NE]

The third one:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-_]+)/$ profile/index.php?username=$1 [QSA,L]
  1. The first removes the .php extension from the URL bar
  2. The third shows the contents of a directory. For example, example.com/billgates/ shows the page content of: example.com/profile/index.php?username=billgates
  3. The second adds a trailing slash and redirects the non-trailing slash of the #2. For example, example.com/billgates redirects to example.com/billgates/ .

All codes work but just not very nicely together. Here is the problem:

If I go to example.com/login it removes the .php extension and it works. BUT the problem is, if I manually add a trailing slash at the end of /login/ , it redirects to: example.com/login/.php/ but it should redirect me to /login because it is not a directory and just a page. But if /login/ was a directory, then it shouldn't redirect.


Full .htaccess:

RewriteEngine On

ErrorDocument 404 /404.php

...the three pieces of codes above

Have it this way and test after clearing browser cache:

ErrorDocument 404 /404.php

RewriteEngine On

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule /$ - [L,R=404]

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


RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/$ profile/index.php?username=$1 [QSA,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