1

问题:

是否可以在%{QUERY_STRING}不破坏我在 .htaccess 文件中完成的任何功能的情况下清除。

我想防止用户添加?foo=bar到 URL 的末尾覆盖任何预定义的 $_GET 变量

(外部重写)示例:

从:example.com/foo/bar/hello/world?test=blah

到:example.com/foo/bar/hello/world

到目前为止,我已经能够做到这一点(内部):

从:example.com/foo/bar/hello/world

到:example.com/index.php?foo=bar&hello=world

.htaccess

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s.+\.(?:html?|php|aspx?) [NC]
RewriteRule ^(.+)\.php$ /$1 [R=301,L,NC]

# To externally redirect /dir/index to /dir/
RewriteCond %{THE_REQUEST} ^GET\s((.+)?(\/)?)?(index) [NC]
RewriteRule ^(([^/]+/)*)index$ /$1 [R=301,L,NC]

# To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_URI} !\.php$ [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule . %{REQUEST_URI}.php [L]

# Prevent Rewrite on existing directories, files, and links
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L] #^ - [L]

# To internally rewrite directories as query string
RewriteRule ^([^/=]+)=([^/]*)(/(.+))?\/?$ /$4?$1=$2 [N,QSA]
RewriteRule ^([^/=]+)/([^/=]+)(/(.+))?\/?$ /$4?$1=$2 [N,QSA]
RewriteRule ^([^/=]+)(/(.+))?\/?$ /$3?$1 [N,QSA]

我试过的:

#if there is a query string
RewriteCond %{QUERY_STRING} ^(.*)$ 
RewriteRule (.*) $1? [R=301,L] #remove query string

-

#if there is a query string
RewriteCond %{QUERY_STRING} !=""
RewriteRule (.*) $1? [R=301,L] #remove query string

-

#if there is a query string
RewriteCond %{QUERY_STRING} !=""
RewriteRule ^(.*)$ $1? [R=301,L] #remove query string

我在某处读到并经历过,应用上述内容会破坏我已经完成的任何事情。如果它们被屏蔽 $_GET 变量,则完全清除整个 url。甚至崩溃 apache 0.o(请原谅我有任何愚蠢的正则表达式或 .htaccess 代码,它们不是我的强大套件,其中大部分是我在 SO 上找到的片段)

这可能吗?我做错了什么?

谢谢

4

1 回答 1

3

尝试:

RewriteCond %{THE_REQUEST} \?[^\ ]+
RewriteRule (.*) /$1? [R=301,L] #remove query string

您需要匹配实际请求,因为您正在使用以下规则构建查询字符串:

# To internally rewrite directories as query string
RewriteRule ^([^/=]+)=([^/]*)(/(.+))?\/?$ /$4?$1=$2 [N,QSA]
RewriteRule ^([^/=]+)/([^/=]+)(/(.+))?\/?$ /$4?$1=$2 [N,QSA]
RewriteRule ^([^/=]+)(/(.+))?\/?$ /$3?$1 [N,QSA]

当这些规则循环时,%{QUERY_STRING}变量中会包含一些东西,而你的规则会破坏它们。如果您与实际请求相匹配,您的重写将不会受到影响。

于 2012-10-20T13:13:23.867 回答