htaccess RewriteRule *.php to /*/

2019-07-13 02:55发布

I just can't find correct solution for what I need, so I hope someone will be able to help me here.

I now have website with this files:

/admin/
/images/
/js/
about.php
index.php
news.php
questions.php

So my URLs now are: www.mydomain.com/about.php www.mydomain.com/news.php ...

I would like to have www.mydomain.com/about/, www.mydomain.com/news/,...

I have tried many things which I found but none of them works like it should or it messes something else up.

The closest I got to is this:

RewriteRule about/ about.php
RewriteRule about about.php

But this also messes up if I use some image in code containing name about (example images/about-me.jpg) - probably because of second statement.

3条回答
做个烂人
2楼-- · 2019-07-13 03:15

this worked for me

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(about)$ about.php
查看更多
Viruses.
3楼-- · 2019-07-13 03:32

Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

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

## To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_FILENAME}.php [L]
查看更多
迷人小祖宗
4楼-- · 2019-07-13 03:32

To make life simpler I would stop using the directory based URL

/about/

and use a simpler file base URL

/about

That extra slash moves the page into a sub directory and all your relative references in the page will break.

Alternatively you can change all your links, includes and image URLs to make sure they all are relative to the root of the domain. You do this by always including a slash (/) before the URL or making them a full URL.

And make your rule more specific:

RewriteRule ^/about$ about.php

Those extra ^$ indicate start and end so it has to be an exact match.

查看更多
登录 后发表回答