简体   繁体   中英

mod_rewrite: remove query string from URL?

I'm trying to make the following redirection (301) using .htaccess

*?page=1 redirects to *

(where * is a wildcard).

Basically, I just want to prevent anyone accessing a page with ?page=1 at the end of the URL, and instead direct them to the same url minus ?page=1 .

Is there a quick way of doing this?

This should do it:

RewriteEngine    On
RewriteCond      %{QUERY_STRING}    ^page=1$
RewriteRule      (.*)               $1?     [R=permanent]

Line by line:

  1. You turn on the rewriting functionality.
  2. You specify as a condition ("if statement") that the query string has to be exactly page=1 for the following rules to apply.
  3. Then you specify a rule that says substitute the entire path (.*) with itself ($1), but make the query string empty (?), and make the result a permanent redirect (301).

If you want the redirect to be temporary (302) then you can just remove the =permanent part. Moved Temporarily is the default for the R flag.

您还可以使用QSD标志(查询字符串丢弃)重定向某处而不传递查询字符串。

If you are on Apache 2.4 You can simply use the QSD (Query String Discard flag) to discard the specific query strings from your destination url.

Here is an example for Apache 2.4 users :

Old url : - /foo/bar/?page=1

new url : - /foo/bar/

Htaccess code :

 RewriteEngine on

 RewriteCond %{THE_REQUEST} \?page=1\sHTTP [NC]
RewriteRule ^ %{REQUEST_URI} [L,R,QSD]

The Rule above will redirect any uri with ?page=1 to remove the query strings. This example will return 500 error on Apache versions bellow 2.4 as They don't support QSD.

On lower versions of Apache, you may use an empty question mark ? at the end of the destination url to remover query strings.

An example :

 RewriteEngine on

 RewriteCond %{THE_REQUEST} \?page=1\sHTTP [NC]
RewriteRule ^ %{REQUEST_URI}? [L,R]

The example above works almost on all versions of apache.

(Hope this helps!)

要剥离整个查询字符串,这就足够了:

RewriteRule ^(.*) http://domain.com/$1? [R=301,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM