Mod重写路径问题

Ant*_*thy 4 php regex .htaccess mod-rewrite lamp

我已经成功创建了重写规则来处理像

http://example.com/xyz

http://example.com/xyz/

http://example.com/xyz/abc

http://example.com/xyz/abc/

这是mod重写和正则表达式:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^/?([0-9]+)(?:\/)?$ /index.php?p=$1 [L]
RewriteRule ^/?([-a-zA-Z0-9_+]+)(?:\/)?$ /index.php?n=$1 [L]
RewriteRule ^/?([-a-zA-Z0-9_+]+)/([-a-zA-Z0-9_+]+)(?:\/)?$ /index.php?n=$2 [L]
Run Code Online (Sandbox Code Playgroud)

这很好用,但问题是,当我访问http://example.com/xyz/abc时,我的脚本获得正确的输入(n = abc),但是路径混乱,所以我的代码中的所有相对URL因为它们现在相对于xyz而不是根目录而被打破.

有没有办法解决这个问题?正如您在上面所看到的,我尝试重定向到/index.php以强制路径正确.经过一整天的正则表达式和代码后,我的大脑被炸了,所以我希望这不是灾难性的微不足道的事情.

Wel*_*bog 8

使用HTML base元素强制所有相对URL使用与浏览器显示的路径不同的路径.

<base href="http://www.example.com/"/>
...
<a href="relative/url">link</a>
Run Code Online (Sandbox Code Playgroud)

相对URL将使用" http://www.example.com "作为其基础,即使浏览器认为它正在查看页面" http://www.example.com/xyz/ ".所以链接转到" http://www.example.com/relative/url "而不是" http://www.example.com/xyz/relative/url "

并且有Stack Overflow方法,其中每个URL都是绝对路径(对于像图像这样的资源)或包含根的路径(即"/ feeds/questions/123"),这避免了相对路径问题.


Fen*_*ton 7

三个选项是:

1)使用基本标记(这将影响页面上的每个相对URI,包括链接,图像,脚本,样式表等)

<base href="http://yoursite/">
Run Code Online (Sandbox Code Playgroud)

2)将所有链接更改为完全限定的URI

<a href="http://yoursite/yourpage.html">
Run Code Online (Sandbox Code Playgroud)

3)使用"/"前缀表示路径相对于每个URI上的根.

<a href="/yourpage.html">
Run Code Online (Sandbox Code Playgroud)

我个人最常使用了base-tag选项,这确实会产生一些糟糕的压力(来自使用它的人并没有真正了解它).当谈到mod_rewrite时,基本标记是完美的,因为您可能希望所有路径都相对于根,包括所有图像,CSS,脚本和链接.