Removing the .php file extension from the URL Request

旧时模样 提交于 2019-12-11 00:36:35

问题


I am trying to beautify my URLs and want to get rid of the .php file extension. I've found a couple of other questions here such as this one (Removing the PHP file type extension) But none of the suggestions work for me. They send me to my 404.php or do not change the URL at all.

I figure the entire RewriteEngine code in my htaccess as a whole is conflicting in itself.

Here's what I got so far,

<IfModule mod_rewrite.c>
    RewriteEngine On

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

    RewriteCond %{SERVER_PORT} !^443$
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


    RewriteBase /
    RewriteRule ^index\.php$ - [R]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /404.php [R]
</IfModule>

I would like my domains to look like

https://www.example.com/about


回答1:


Don't mix Redirect, RedirectMatch and RewriteRule directives in same .htaccess as they come from different Apache modules and their load sequence is unpredictable.

Have it this way:

ErrorDocument 404 /404.php
RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301,NE]

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]

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

Make sure to clear your browser cache before testing this change.




回答2:


Put in .htaccess

RewriteEngine on

RewriteBase /

RewriteCond %{REQUEST_METHOD} POST
RewriteRule ^ - [L]

#1)externally redirect "/file.php" to "/file"
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R]

#2)Internally map "/file" back to "/file.php"
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ /$1.php [NC,L]

ErrorDocument 404 ./404
RewriteCond %{REQUEST_URI} ^404/$
RewriteRule ^(.*)$ ./404 [L]

Redirect 301 /index /



回答3:


remove .php from the link :

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


来源:https://stackoverflow.com/questions/51504638/removing-the-php-file-extension-from-the-url-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!