与htaccess的相对URLhtaccess、URL

2023-09-02 00:53:22 作者:一年硬两次

我在该领域后,一切都发送到PHP作为$ _GET变量自定义的PHP框架,就像这样:

I have a custom PHP framework in which everything after the domain is sent to PHP as a $_GET variable, like so:

重写规则^(。*)$的index.php?page_request = $ 1 [QSA,L]

所有的路由是由路由器文件来完成。例如,的http://domain.tld/page 被发送到的http://domain.tld page_request =家庭

All routing is done by a router file. For example, http://domain.tld/page gets sent to http://domain.tld?page_request=home.

不过,如果我有一个目录状结构(即的http://domain.tld/page/ ),请求被发送,但是任何的在HTML相对URL 的现在相对 /页,尽管我们仍然在域中的根目录下。

However, if I have a directory-like structure (i.e. http://domain.tld/page/), the request is sent, but any relative URLs in the HTML are now relative to /page, even though we're still in the root level in the domain.

要澄清:

的http://domain.tld/page ,并请求 RES / CSS / style.css中的HTML返回一个样式表。

Going to http://domain.tld/page and requesting res/css/style.css in HTML returns a stylesheet.

的http://domain.tld/page/ ,并请求 RES / CSS / style.css中返回404错误,因为页/ 目录实际上并不存在。

Going to http://domain.tld/page/ and requesting res/css/style.css returns an 404 error, because the page/ directory doesn't actually exist.

什么是解决这一问题的最佳方法是什么?这似乎很简单,但我不够好带的.htaccess还没有做到这一点从我的头顶。感谢提前任何答案。

What's the best way to work around this? This seems really simple, but I'm not quite good enough with .htaccess yet to do it off the top of my head. Thanks for any answers in advance.

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

编辑#2:是的,我知道如何使用领先的/.

不过,我不能做到这一点与这个特定的网站,因为它是一个服务器上的一个子文件夹,所以链接到 / 将转至服务器的根目录,不是网站。

Edit #2: Yes, I know about using the leading /.

However, I can't do that with this particular website, because it's a subfolder on a server, so linking to / would go to the root of the server and not the site.

如果我把 /子文件夹/ CSS 网​​站上的每一个环节,这不仅会让人觉得无聊,但也存在问题是子文件夹改变。有没有更好的方法来解决此问题?

If I put /subfolder/css for every link on the site, that would not only get tedious, but also problematic were the subfolder to change. Is there a better way to work around this?

推荐答案

这是说你有绝对化的路径是正确的答案。如果你工作在一个子文件夹中,有两件事情,你可以/应该做的帮助:

The other answers that say you have to absolutize the paths are correct. If you are working in a subfolder, there are two things that you can/should do to help:

1)使用的RewriteBase 在你的htaccess文件

1) Use RewriteBase in your htaccess file

RewriteEngine on
RewriteBase /framework/

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/?$    index.php?url=$1    [QSA,L]

2)创建一个常数的框架,具有相同的路径

2) Create a constant in your framework that has that same path

define('FULL_PATH', '/framework');

然后每次创建在HTML中的URL,确保你做这样的事情

Then each time you create a URL in html, make sure you do something like

<a href="<?= FULL_PATH ?>/your/remaining/path">

这是额外的工作,你在页面上创建一个URL每次想到这一点,但它会满足你的需要,从长远来看。

It's a little bit of extra work to think about this each time you create a URL on the page, but it will serve you well in the long run.