1

我正在创建一个新网站,其中包含一些 php。该网站基本上会像这样工作,我有/index.php?page=category_page。类别将是类别,页面将是子类别/实际页面的排序。重写后的规则如下所示:/category/page。

我有这个:

RewriteEngine On
RewriteRule ^category/([^/]*)$ index.php?page=$1 [L]

但是我不知道如何将类别和页面分开,有什么帮助吗?第二件事是,在我的 index.php 中(例如)我有一些来自外部文件的 css:

<link rel="stylesheet" type="text/css" href="style/style.css"/>

这不适用于重写规则,因为它尝试加载不存在/不重写的 /category/page/style/style.css。我如何使它工作?我知道一个简单的解决方法是放置 /style/style.css 并且将从网站的根目录加载,但我目前正在从子目录运行网站,例如 example.com/new/index.php 以便不是一个选择。有什么帮助吗?

4

2 回答 2

3

Problem 1:

You could define multiple parameters in your regex, e.g. category & page (see below).

With such a broad rewrite rule, you would want to add a condition not to rewrite for stylesheets, images, and other assets, though.

I also modified your pattern to only match letters, digits, hyphens, and underscores, which would prevent the use of non-standard characters in your category or page names.

RewriteEngine On
RewriteCond %{REQUEST_URI} !\.(js|css|png|gif|jpg)$ [NC]
RewriteRule ^([\w\d\-]+)/([\w\d\-]+)/?$ index.php?category=$1&page=$2 [L]

Problem 2:

You're using a relative url in your href, which is appending the stylesheet's location to the current location defined in your browser (/category/page/).

Even though the server-side is rewriting that URL, the browser is unaware of the rewrite.

If you use an absolute URL instead, your browser will define the URL relative to the BASE url (/).

Try this:

<link rel="stylesheet" type="text/css" href="/style/style.css"/>
于 2013-10-31T12:29:58.167 回答
1

Use this RewriteRule

RewriteEngine On
RewriteRule ^(.+)/(.+)/$ index.php?page=$1_$2 [L]
于 2013-10-31T12:31:50.147 回答