将所有流量重定向到不带任何参数的index.php



让我向你介绍我的问题。我是。htaccess的新手…直到我的.htaccess工作得很好,这是我使用的两个url参数的代码(例如www.page.com/en/articles):

)
# DISABLE CACHING
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
Header set Access-Control-Allow-Origin "*"
</IfModule>
Options -Indexes
RewriteEngine on
RewriteCond %{HTTPS} on
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ index.php [R=301,L]
RewriteRule ^([^/]*)(.*)$ index.php?lang=$1&url=$2 [L]

但是当我添加第三个参数像这样(f.e. www.page.com/en/articles/20):

...
RewriteRule ^([^/]*)(.*)$ index.php?lang=$1&url=$2&id=$3 [L]

echo $_GET['lang']返回"en"但是echo $_GET['url']返回了"/articles/20"$_GET['id']不存在

谁能给我解释一下我到底做错了什么?

Thanks in advance

编辑

文件夹结构:

. htaccess

index . php

主题:pages | classes…

assets: images | style | js…

与其在apache配置中编写越来越复杂的正则表达式,不如将所有内容批量重写为index.php,然后在应用程序中进行解析。不管怎样,你已经使用index.php作为请求路由器了。

// eg: /en/articles/20?other_query=vars&might=be_here
$uri = $_SERVER['REQUEST_URI'];
$parts = explode('/', parse_url($uri)['path']);
var_dump($parts);

输出:

array(4) {
[0]=>
string(0) ""
[1]=>
string(2) "en"
[2]=>
string(8) "articles"
[3]=>
string(2) "20"
}

你有更多/更好的工具来解析PHP中的URI。

这也有一个额外的效果,使你的应用程序更容易移植,因为如果你移动到另一个HTTPd,如nginx,你不需要重新实现那么多配置。

如果你想捕获最多一个/,那么试试:

RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ index.php?lang=$1&url=$2&id=$3 [L]

但最好是三种情况下注意没有[L]:

RewriteRule ^([^/]*)$ index.php?lang=$1
RewriteRule ^([^/]*)/([^/]*)$ index.php?lang=$1&url=$2
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ index.php?lang=$1&url=$2&id=$3

要排除一个目录,如'images ',使用pass-thru。如果它们不在另一个目录中,则必须匹配类型或扩展名。在其他规则之前执行:

RewriteRule ^images/.*$ - [PT]

From Sammitch, RewriteCond将防止触发重写规则,如果该名称的实际文件存在。如果存在合适的DirectoryIndex配置,目录也有-d:

RewriteCond %{REQUEST_FILENAME} !-f 

相关内容

最新更新