How to remove any query except `callback` for specific URLs with RewriteRule?

依然范特西╮ 提交于 2019-12-11 14:07:49

问题


The current RewriteRule removes any query except query callback for any URL.

# Remove question mark and parameters
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^?#\ ]*)\?[^\ ]*\ HTTP/ [NC]
# Query rewrite exceptions
##RewriteCond %{REQUEST_URI}?%{QUERY_STRING} !^/api.*?callback=.* #does not work
RewriteCond %{QUERY_STRING} !callback=
RewriteRule .*$ %{REQUEST_URI}? [R=301,L]

How to avoid query callback rewrite just from URL ^api\/?([^\/]*)$? Excepted result:

  • no rewrite for /api?callback=1, /api/user?callback=1, /api/user/2?callback=1
  • rewrite for /apis?callback=1, /user?callback=1, /api/user?foo=1 etc.

回答1:


I finally understood your question...

Replace these lines:

##RewriteCond %{REQUEST_URI}?%{QUERY_STRING} !^/api.*?callback=.* #does not work
RewriteCond %{QUERY_STRING} !callback=

with this line:

RewriteCond %{REQUEST_URI}?%{QUERY_STRING} !^/api(/.*)?\?callback=.*

Important notice:

if your script isn't located in the document root, but, i.e., in dir /htest, and full URL looks like mine: http://localhost/htest/api/?callback=1, then you have to put full path to API in your RewriteCond:

RewriteCond %{REQUEST_URI}?%{QUERY_STRING} !^/htest/api(/.*)?\?callback=.*

You can overcome that by beginning your regex with !/api instead of ^/path/to/api, but /foo/api and /bar/api will be skipped from rewriting too.

Update:

this .htaccess works fine in document root:

RewriteEngine On

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^?#\ ]*)\?[^\ ]*\ HTTP/ [NC]
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} !^/api(/.*)?\?callback=.*
RewriteRule .*$ %{REQUEST_URI}? [R=temporary,L]

you may try using it without any other rules to check what is wrong

Update 2

If you have other condition, i.e.,

RewriteRule ^([^.]*)$ index.php?url=$1 [QSA,L]

repeat RewriteCond before it:

RewriteCond %{REQUEST_URI}?%{QUERY_STRING} !^/api(/.*)?\?callback=.*
RewriteRule ^([^.]*)$ index.php?url=$1 [QSA,L]

also to be able to use these rules in /foo subdir, replace ^/api with ^/foo/api




回答2:


To enable RewriteRule for index.php, need to add in query rewrite exceptions.

This rules works fine and fixes this issue:

# Remove question mark and parameters
RewriteCond %{QUERY_STRING} .+
# Query rewrite exceptions
RewriteCond %{REQUEST_FILENAME} !index.php
RewriteCond %{REQUEST_URI}?%{QUERY_STRING} !/api(/.*)?\?callback=.*
RewriteRule .*$ %{REQUEST_URI}? [R=301,L]


来源:https://stackoverflow.com/questions/12509120/how-to-remove-any-query-except-callback-for-specific-urls-with-rewriterule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!