简体   繁体   中英

Hide extension of php files and hide index.php with htaccess

This has been asked a thousand times, but not exactly how I want it. I have tried combining different solutions, but my .htaccess doesn't seem to do what it is supposed to.

# 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 correctly change from domain.com/page1.php to domain.com/page1 , however something goes wrong with domain.com/index.php .

I am testing this locally and when going to localhost/project everything works fine (the index.php opens, but you don't see that in the url) but when you explicitly navigate to localhost/project/index.php you are returned to the very root, ie localhost (which hen returns to http://localhost/xampp/splash.php ). Of course, this is not what I want. I want localhost/project/index.php to return to `localhost/project/´.

An additional question, though: how do rewrite rules influence search engines. Will the pages (ie contact.php, about-us.php and so on) still be indexed?

Extra +1 and kudos for he or she who gives a detailed breakdown of what each line/rule in the htaccess in their answer does. I am still learning .htaccess, so every detail is important and relevant to me!

Lot of comments in this code in question seem to be mine :)

Anyway you can use this code to fix your issue:

# 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 using 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]

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