LOTUSMS
LOTUSMS

Reputation: 10240

Removing the .php file extension from the URL Request

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

Upvotes: 2

Views: 142

Answers (3)

Fobos
Fobos

Reputation: 1156

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 /

Upvotes: 1

anubhava
anubhava

Reputation: 785146

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.

Upvotes: 1

Mohammad
Mohammad

Reputation: 1577

remove .php from the link :

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

Upvotes: 0

Related Questions