简体   繁体   中英

PHP rewriting URL to remove .php extension

I am working on a project where I decided to get rid of the.php extension from the URL of my app. I am successful using the htaccess code given below. But the problem is, the page still loads using.php extension if typed manually or loaded from the history.

My current .htaccess code.

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

I want it to always load with www.example.com/dashboard except www.example.com/dashboard.php even if dashboard.php is manually typed.

UPDATED .htaccess code

RewriteEngine On
RewriteBase /dateapp/
RewriteRule ^([^\.]+).php$ $1 [R]

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

You can add redirect as first rule.

RewriteEngine On
RewriteRule ^([^\.]+).php$ /$1 [R]

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

You have to use END flag instead of L otherwise the redirects will end in infinite loop. This will work if the .htaccess is in your webroot folder.

In case you have .htaccess in 'folder' subfolder you will have to add RewriteBase

RewriteEngine On
RewriteBase /folder/
RewriteRule ^([^\.]+).php$ $1 [R]

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

You may use this code in dateapp/.htaccess :

RewriteEngine On
RewriteBase /dateapp/

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ %1 [R=301,NE,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [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