Hide php file extension and hide index.php with htaccess

This has been asked a thousand times, but not quite the way I want it. I tried to combine different solutions, but my .htaccess doesn't seem to do what it should.

# Not sure what this does?
Options +FollowSymLinks -MultiViews

# Turn mod_rewrite on
RewriteEngine On

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

# Redirect index in any directory to root of that directory
RewriteCond %{THE_REQUEST} ^[A-Z](3,9)\ /([^/]+/)*index\.[^\ ]*\ HTTP/
RewriteRule ^(([^/]+/)*)index(\.[a-z0-9]+)?$ http://www.example.com/$1? [R=301,L] 

      

Now my pages are changing correctly from domain.com/page1.php

to domain.com/page1

, however there is something wrong with domain.com/index.php

.

I'm testing this locally, and when navigating to localhost/project

everything works fine (opens index.php

but you don't see it in the url), but when you explicitly navigate to localhost/project/index.php

, you fall back to very root i.e. localhost

(the chicken returns to http://localhost/xampp/splash.php

). Of course, this is not what I want. I want to localhost/project/index.php

go back to `localhost / project / '.

Another question: how do rewrite rules affect search engines. Will the pages (i.e. contact.php, about-us.php, etc.) still be indexed?

Extra +1 and prestige for someone giving a detailed description of what each line / rule in htaccess does in their response. I am still learning .htaccess so every detail is important and relevant to me!

+3


source to share


1 answer


Lots of comments in this code seem to be mine :)

Anyway, you can use this code to fix your problem:

# Turn mod_rewrite on
RewriteEngine On
RewriteBase /project/

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s/+project/+(.*?/)?(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ %1%2 [R=302,L,NE]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/project/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]

      



Update: For use in DocumentRoot

:

# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index)?(.*?)\.php[\s?] [NC]
RewriteRule ^ %1%2 [R=302,L,NE]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]

      

0


source







All Articles