我已经阅读并测试了许多解决方案,但无法正常工作。
我需要什么?
如果用户在地址栏中输入.../etc.php
,则应将其重定向到.../etc/
,同时.../etc/
也应该能够直接访问,例如:
www.mysite.com/index.php
- > www.mysite.com/
www.mysite.com/register.php
- > www.mysite.com/register/
www.mysite.com/profile.php?id=123
- > www.mysite.com/profile/123/
此外,如果lang
参数设置为en
(仅en
,否则不会在地址栏显示lang
值)它应该在root后添加/en/
,像:
www.mysite.com/register.php?lang=en
- > www.mysite.com/en/register/
www.mysite.com/index.php?lang=en
- > www.mysite.com/en/
我做了什么
Options -MultiViews
RewriteEngine on
RewriteBase /
# url is ONLY '/en' or '/de' -> redirect to /en/ or /lt/ (adding slash)
RewriteRule ^(en|lt)$ $1/ [R=301,L]
# now all urls have en/ lt/ -> parse them
RewriteRule ^(en|lt)/(.*)$ $2?lang=$1&%{query_STRING} [L]
# no "R=301" here --------------------------------------^
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
但上面的代码允许用户同时访问www.mysite.com/register.php
和www.mysite.com/register/
,而它应该从www.mysite.com/register.php
重定向(更改网址)到www.mysite.com/register/
答案 0 :(得分:1)
我建议这个重定向规则从网址中删除.php
个扩展名和index.php
:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} /+(.*?/)?(?:index)?(.*?)\.php[/\s?] [NC]
RewriteRule ^ %1%2/ [R=302,L,NE]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]