如果URL包含特定的字符串,如何使RewriteRule工作?

时间:2015-03-11 03:59:25

标签: .htaccess

我需要添加RewriteRule,只有在URL中有某个字符串时才有效,否则我需要从另一个文件夹加载内容。如果URL包含字符串test,我需要将其作为参数发送到index.php,否则应从directory文件夹加载内容。

例如:项目的根文件夹是new_project。如果网址为http://localhost/new_project/test/something/,那么我需要将test/something/作为参数发送到index.php。如果URL类似于http://localhost/new_project/something/,那么我需要从directory/something文件夹加载内容。

以下是我目前撰写的.htaccess文件:

Options +FollowSymLinks
RewriteEngine on

# Force Trailing Slash
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

# Send request via index.php (again, not if its a real file or folder)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

# Serve other requests from the directory/ folder
RewriteRule ^(.*)$ directory/$1 [L]

上述.htaccess文件中需要更改的内容,以便URL中test字符串的出现将字符串test后面的字符串与字符串{{1}一起传递} test如果网址不包含字符串index.php,则从test文件夹中加载内容?

1 个答案:

答案 0 :(得分:1)

您可以测试test/内部的RewriteRule。在" catch-all"之前放置更具体的重写规则。 directory/重写规则。

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

# All requests starting with `test/` go to index (without the `test` part).
RewriteRule ^test/(.*)$ index.php?/$1 [L] # Not sure how GET parameters starting with `?/` behave.

# All others go to directory. Assuming not a valid file or dir.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ directory/$1 [L]