简体   繁体   中英

Remove php extension from URL - except one and only one URL using htaccess

I'm using this code to remove the .php from the end of my URL's making them more SEF.

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(.+)\.php[^\s]* [NC]
RewriteRule ^ /%1 [R=301,NE,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [QSA,NC,L]

This is generic and works perfectly for every UR but I would like to know how to create an exception for one and only one URL , ie: http://www.domain.com/services to http://www.domain.com/services.php without influencing all the others. Is this possible?

I've tried a simples Redirect but entered a loop.

! EDITED !

I failed to mention I have also these rules:

Add www.

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Remove index (the extension .php from index has been trimmed already)

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index/?([^\ \?]*) [NC]
RewriteRule ^ %1/%2 [R=301,L]

You should :

  • add a RewriteCond , to disabled services.php => services
  • add another rule, to enforce services => services.php , as the first rule doesn't prevent user to manually use services url

Full .htaccess

# domain.tld > www.domain.tld (visible)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# services > services.php (visible)
RewriteRule ^services/?$ services.php [R=301,QSA,L]

# filename > filename.php (transparent)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [QSA,NC,L]

# filename.php > filename (visible, exception for services.php)
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(.+)\.php[^\s]* [NC]
RewriteCond %{REQUEST_FILENAME} !services\.php
RewriteRule ^ /%1 [R=301,NE,L]

# index > /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index/?([^\ \?]*) [NC]
RewriteRule ^ %1/%2 [R=301,L]

I would believe just a small change in your .php removal rule should do the job:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(.+?)\.php[\s?] [NC]
RewriteRule !^services\.php$ /%1 [R=301,NE,NC,L]

Can you try this,

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

You can add one rule for each php file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^services  /services.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