要如何把所有子目录使用的htaccess或httpd.conf来根?子目录、htaccess、conf、httpd

2023-09-02 09:43:57 作者:喜旧.

我有基于建立内容索引文件的 N 的PATH_INFO变量。

I have an index file that builds content based on n PATH_INFO variables.

例如:

site.com/A/B/n/

应该使用的index.php在任:

should use index.php at either:

site.com/index.php?var1=A&var2=B&varN=n
 - or - 
site.com/index.php/A/B/n/

来代替:

site.com/A/B/n/index.php || which doesn't exist ||

到目前为止,我已经尝试了一些变化:

So far I've tried a number of variations of:

RedirectMatch ^/.+/.*$ /

没有成功。

我有一个不雅的和不可扩展的解决方案在这里:

I have an inelegant and unscalable solution here:

RewriteEngine On 
RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?p1=$1 [NC,L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?p1=$1&p2=$2 [NC,L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?p1=$1&p2=$2&p3=$3 [NC,L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?p1=$1&p2=$2&p3=$3&p4=$4 [NC,L]

这个解决方案的问题:

不雅和不可扩展,需要手动线每个子目录 失败,非字母数字字符(主要是+,=和&安培;)前。 site.com/ab&c/de+f/ (注意,甚至改变了正则表达式^([A-ZA-Z0-9 _- + = &安培; ] +)/ $没有多大帮助,实际上使得报错了完全? ) Inelegant and unscalable, requires manual line for each subdirectory Fails with non alphanumeric characters (primarily +,= and &) ex. site.com/ab&c/de+f/ (note, even changing the regex to ^([a-zA-Z0-9_-+=&]+)/?$ does little to help and actually makes it error out entirely)

你能帮忙吗?

推荐答案

选项1:( site.com/index.php?var1=A&var2=B& VARN = N ):

Options +FollowSymLinks -MultiViews
RewriteEngine On

# do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]

RewriteRule ^([^/]+)/?$ index.php?p1=$1 [QSA,L]
RewriteRule ^([^/]+)/([^/]+)/?$ index.php?p1=$1&p2=$2 [QSA,L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ index.php?p1=$1&p2=$2&p3=$3 [QSA,L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ index.php?p1=$1&p2=$2&p3=$3&p4=$4 [QSA,L]

1。你有 [NC] 标志...所以没有必要有 AZ 在你的模式。

1. You had [NC] flag ... so there were no need to have A-Z in your pattern.

2。相反的[A-ZA-Z0-9 _- + = &安培] [A-ZA-Z0-9 _-] 我用 [^ /] 这意味着除了斜线任意字符/ 的。

2. Instead of [a-zA-Z0-9_-+=&] or [a-zA-Z0-9_-] I use [^/] which means any character except slash /.

3。 [QSA] 标记添加到preserve现有的查询字符串。

3. [QSA] flag was added to preserve existing query string.

选项2:( site.com/index.php/A/B/n / ):

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php/$1 [L]

在现实中,如果你不打算在任何地方显示的URL(如,301重定向等),最后一行可以很容易地通过重写规则所取代。*的index.php [L] - 你将寻找原始URL使用 $ _ SERVER ['REQUEST_URI'] 在你的PHP code反正

In reality, if you do not plan to show that URL anywhere (like, 301 redirect etc), the last line can easily be replaced by RewriteRule .* index.php [L] -- you will look for original URL using $_SERVER['REQUEST_URI'] in your PHP code anyway.

 
精彩推荐
图片推荐