大网数据广告活动
服务器运维问答

RewriteCond ignored in httpd.conf

· 52CE 我爱测

Put simply this works in htaccess: RewriteEngine on RewriteCond %{SCRIPT_FILENAME} !-f RewriteCond %{SCRIPT_FILENAME} !-d RewriteRule ^([^/]+)/?$ https://example.net?u=$1 [L,NC,R=301] But when I move it to httpd.conf it does noth…

问题原文

原帖链接 · Guesser · CC BY-SA 4.0

Put simply this works in htaccess:

RewriteEngine on

RewriteCond %{SCRIPT_FILENAME} !-f 
RewriteCond %{SCRIPT_FILENAME} !-d 

RewriteRule ^([^/]+)/?$ https://example.net?u=$1 [L,NC,R=301] 

But when I move it to httpd.conf it does nothing. I have tried in the directory directive and that also makes no difference.

As a test the below in httpd.conf does have an affect, it re-directs, but does so to all pages i.e the condition is ignored.

RewriteEngine on

RewriteCond %{SCRIPT_FILENAME} !-f 
RewriteCond %{SCRIPT_FILENAME} !-d 

RewriteRule ^(.*)$ https://example.net?u=$1 [L,NC,R=301] 

已采纳解答

原帖链接 · DocRoot · CC BY-SA 4.0

RewriteRule ^([^/]+)/?$ https://example.net?u=$1 [L,NC,R=301] 

But when I move it to httpd.conf it does nothing.

Because in a server context the RewriteRule pattern will never match. In a server context the URL-path is root-relative, starting with a slash. In .htaccess the URL-path is less the directory-prefix, so never starts with a slash.

I have tried in the directory directive and that also makes no difference.

That should have worked, providing you included the correct directory path. (And restarted Apache.) However, if you still had a .htaccess file that enabled the rewrite engine then this would have overridden the server directives in the <Directory> container, so the <Directory> directives wouldn't have done anything still.

As a test the below in httpd.conf does have an affect, it re-directs, but does so to all pages i.e the condition is ignored.

RewriteEngine on

RewriteCond %{SCRIPT_FILENAME} !-f 
:

Because in a server context the request has not yet been mapped to the filesystem, so SCRIPT_FILENAME (or REQUEST_FILENAME) does not yet contain the full filesystem path (it simply contains the URL-path), so this condition always evaluates to true (the "URL-path" being tested is not a physical file - which is probably correct).

You need to use a look-ahead instead in order to determine the final value. ie. %{LA-U:REQUEST_FILENAME}.

So, in a server (or virtualhost) context you would need to use the following instead:

RewriteEngine on

RewriteCond %{LA-U:REQUEST_FILENAME} !-f 
RewriteCond %{LA-U:REQUEST_FILENAME} !-d 

RewriteRule ^/([^/]+)/?$ https://example.net?u=$1 [L,R=301] 

Note the slash prefix on the RewriteRule pattern.

The NC flag is superfluous here.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-10-29)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。