简体   繁体   中英

.htaccess rewrite help, remove .php from URL

I am not facing another problem with my mod_rewrite, first, time is my .htaccess file:

Options +FollowSymlinks
RewriteEngine on

RewriteRule ^news/([0-9]+)/?$ /news?id=$1 [L,QSA]
RewriteRule ^contact/([0-9]+)/?$ /contact?do=$1 [L,QSA]
RewriteRule ^account/([a-zA-Z]+)/?$ /account?action=$1 [L,QSA]
RewriteRule ^admin/([a-zA-Z]+)/?$ /admin?action=$1 [L,QSA]
RewriteRule ^login/([a-zA-Z]+)/?$ /login?action=$1 [L,QSA]
RewriteRule ^register/([a-zA-Z]+)/?$ /register?action=$1 [L,QSA]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L] <- This line doesn't work
RewriteRule ^([\w\d~%.:_\-]+)$ index.php?page=$1 [L,QSA]

All lines are working, beside the RewriteRule ^([^.]+)$ $1.php [NC,L] and when I use this line, all other rules gets interrupted.

What am I doing wrong?

You need to use L flag in your problematic rule.

For removing the .php extension this is better rule:

Options +FollowSymlinks -MultiViews

RewriteEngine on

## If the request is for a valid directory
RewriteCond %{REQUEST_FILENAME} -d [OR]
## If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f [OR]
## If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} -l
## don't do anything
RewriteRule ^ - [L]

RewriteRule ^news/([0-9]+)/?$ /news?id=$1 [L,QSA]
RewriteRule ^contact/([0-9]+)/?$ /contact?do=$1 [L,QSA]
RewriteRule ^account/([a-zA-Z]+)/?$ /account?action=$1 [L,QSA]
RewriteRule ^admin/([a-zA-Z]+)/?$ /admin?action=$1 [L,QSA]
RewriteRule ^login/([a-zA-Z]+)/?$ /login?action=$1 [L,QSA]
RewriteRule ^register/([a-zA-Z]+)/?$ /register?action=$1 [L,QSA]

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

RewriteRule ^(.+?)/?$ index.php?page=$1 [L,QSA]

Try something like

#Preventing loop 
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]

RewriteCond %{REQUEST_URI} !^.+\.php.*$
RewriteRule .* - [L]

Put this after RewriteRule ^register/([a-zA-Z]+)/?$ /register?action=$1 [L,QSA]

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