【问题标题】:.htaccess remove query string, keeping SEO style url.htaccess 删除查询字符串,保留 SEO 风格的 url
【发布时间】:2012-10-10 22:05:01
【问题描述】:

问题:

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

我想防止用户在 URL 末尾添加 ?foo=bar 覆盖任何预定义的 $_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 上找到的 sn-ps)

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

谢谢

【问题讨论】:

    标签: .htaccess mod-rewrite apache2


    【解决方案1】:

    试试:

    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} 变量中会包含一些东西,而您的规则会破坏它们。如果您匹配实际请求,您的重写不会受到影响。

    【讨论】:

    • 与其他人获得 403 时遇到的相同错误,看起来它删除了查询字符串。但是 url 被重写为 example.com/C:/PATH/TO/SITE/DIRECTORY/www/foo/bar (在使用 xampp 测试的 windows 机器上,目标机器是 *nix 机器,不确定这是否会影响它)
    • @StrikeForceZero 哦,所以您要么需要RewriteBase /,要么在规则目标的$1 前面添加/
    • 谢谢您,先生,您真是个天才! =) (因为我正在浏览你的网站等待回复哈哈,所以我会看看你的安卓应用程序)
    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多