htaccess RewriteRule *.php to /*/

元气小坏坏 提交于 2019-12-10 23:57:14

问题


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.


回答1:


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]



回答2:


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.




回答3:


this worked for me

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(about)$ about.php


来源:https://stackoverflow.com/questions/13800070/htaccess-rewriterule-php-to

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