apache - 未知目录的重写规则

标签 apache .htaccess mod-rewrite url-rewriting

所以我试图获得一个 mod_rewrite 规则来将请求重定向到一个带有 .htaccess 文件的 php 脚本。问题是,无论我将项目放在网络服务器上的什么位置,我都希望它能够正常工作(.htaccess 文件和 php 脚本始终位于同一文件夹中)。

重写本身非常简单。如果脚本和 .htacess 位于目录 /path/to/project 中并且用户访问:

/path/to/project/somestring

应该重写为:

/path/to/project/index.php?t=somestring

这应该适用于网络服务器中任何级别的每个子目录。所以:

如果 php-script 和 .htaccess 文件在根目录中:

/somestring2

应该重写为:

/index.php?t=somestring2

如果 php-script 和 .htaccess 文件在 /subdirectory 中:

/subdirectory/somestring3

应该重写为:

/subdirectory/index.php?t=somestring3

因此无论项目在服务器中的哪个位置,RewriteRule 都应该执行相同的重写操作。要成为 GET 参数的字符串可以包含以下字符:[a-zA-Z0-9]。如果请求的 URL 中有其他 GET 参数,则也应附加它们(因此 QSA 标志)。这是我试过的:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*/)([a-zA-Z0-9])/? $1index.php&t=$2 [L,QSA] 

但是,这会导致 404 错误。我怎样才能改变它来做我想做的事?

最佳答案

尝试:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*/)?([A-Za-z0-9]+)/?$ /$1index.php?t=$2 [NC,L,QSA]

请注意,在 RewriteRule 上下文中不需要重写模式中的前导斜杠。

关于apache - 未知目录的重写规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34877605/

相关文章:

java - CollectionUtils.isEqualCollection 基数是什么?

javascript - 无法使用 htaccess 加载 css、js 和图像

.htaccess - 带有子目录的 htaccess 多语言站点,默认为 301

regex - Wordpress 子目录上的不同项目

mod-rewrite - Lighttpd重写转换?

php - Slim 框架 - 500 内部服务器错误

apache - socket.io 与 Apache Tomcat

linux - Subversion+Apache authz 未授权

mysql - 使用 lampp 托管时如何修复 "Slim Application Error"错误

regex - 包含双斜杠的重写规则不匹配