如何设置在mod_rewrite的可选参数可选、如何设置、参数、mod_rewrite

2023-09-02 00:27:56 作者:①輩孑嗳伱

我在一个新的项目,我设计的URL结构, 事情是我想要的网址是这样的: /类-23 /关键字/ 5 / 凡正常页面: /search.php?q=keyword&cat=23&page=5 所以我的问题是,猫和页的领域,一定是可选的,我的意思是,如果我去 /关键字它应该 /search.php?q=keyword (第1页) 如果我去 /分类/关键字应该是: /search.php?q=keyword&cat=category&p=1 并且,如果我去 /关键字/ 5 / 它必须是: /search.php?q=keyword&p=5

I am in a new project and I'm designing the URL structure, the thing is I want URLs look like this: /category-23/keyword/5/ Where the normal page is: /search.php?q=keyword&cat=23&page=5 So my question is, cat and page fields, must be optional, I mean if I go to /keyword it should be /search.php?q=keyword (page 1) and if I go to /category/keyword should be: /search.php?q=keyword&cat=category&p=1 and also if I go to /keyword/5/ it must be: /search.php?q=keyword&p=5

现在,我有我的.htaccess这样的:

Now I have my .htaccess like this:

RewriteEngine On
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*)$ search.php?q=$2&cat=$1&page=$3 [L]

我不能让它工作和CSS /图像文件不会加载。 我要感谢很多谁可以给我一个解决方案。

I cannot make it working and the CSS / image files don't load. I'd thank a lot who could give me a solution.

推荐答案

您可以用四个规则,每一个案件做到这一点:

You can do this with four rules, one for each case:

RewriteRule ^([^/]+)$ search.php?q=$1
RewriteRule ^([^/]+)/([0-9]+)$ search.php?q=$2&p=$1
RewriteRule ^([^/]+)/([^/]+)$ search.php?q=$2&cat=$1&p=1
RewriteRule ^([^/]+)/([^/]+)/([0-9]+)$ search.php?q=$2&cat=$1&p=$3

和与此规则中的其他规则前,任何请求可以映射到现有的文件将被通过:

And with this rule in front of the other rules, any request that can be mapped onto existing files will be passed through:

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^ - [L]

现在你的最后一个问题,即外部链接资源不能被发现,是由于你可能使用相对URL路径,比如 CSS / style.css中 ./ CSS / style.css中。这些相对引用从基网址路径是引用中所使用的文档的URL的URL路径解决。因此,在情况下 /类别/关键字请求,如 CSS / style.css中解析为 /category/keyword/css/style.css ,而不是相对引用 /css/style.css 。使用绝对URL路径 /css/style.css 使其独立于实际的基础URL路径

Now your last issue, that externally linked resources cannot be found, is due to that you’re probably using relative URL paths like css/style.css or ./css/style.css. These relative references are resolved from the base URL path that is the URL path of the URL of the document the references are used in. So in case /category/keyword is requested, a relative reference like css/style.css is resolved to /category/keyword/css/style.css and not /css/style.css. Using the absolute URL path /css/style.css makes it independent from the actual base URL path