简体   繁体   中英

How to redirect a page but keep the original URL with htaccess

I'm trying to do this:

domain.com/s/united-states
domain.com/s/singapore
domain.com/s/anything

will redirect to the page of domain.com/s/ , but keeps the original URL which was:

domain.com/s/united-states
domain.com/s/singapore
domain.com/s/anything

The reason I'm doing this is because I am building a search page at domain.com/s/ and using the endpoint of the URL as the search term. I tried the following:

RewriteRule ^s/([a-zA-Z_-]+)$ /s/ [NC,NE,R,L]

which works but does not keep the original URL.

I tried:

RewriteRule ^s/([a-zA-Z_-]+)$ /s/ [NC,NE,L] 

which does not work. May I have your thoughts about it?

The redirect also needs to keep any get parameter at the back like example:

domain.com/s/primary-search-term?filter1=x&filter2=y

This kind of URL handling can be seen in pages like Airbnb:

https://www.airbnb.com/s/Singapore?guests=1&adults=1&children=0&infants=0&ss_id=th87ej7h&source=bb

A snippet of my .htaccess is as below:

## No directory listings
IndexIgnore *

## Can be commented out if causes errors, see notes above.
Options +FollowSymlinks
Options -Indexes

## Mod_rewrite in use.

RewriteEngine On
RewriteRule ^s/([a-zA-Z_-]+)$ /s/ [NC,NE,L]

In case it means anything, this is part of the Joomla default .htaccess with SH404SEF installed.

UPDATE: I tried the following which worked on one test server but failed on production...

RewriteRule ^d/([a-zA-Z_-]+)$ /index.php?option=com_quix&Itemid=876&id=105&lang=en&view=page&fulladdress=$1 [L,QSA]

The output on the access log showed

[07/Feb/2017:08:42:57 +0000] "GET /d/singapore HTTP/1.1" 404 24732 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" www.domain.com:443 124.82.84.207

Everything seems the same.. no idea why it would fail.

You need to drop the R flag as it's designed for external redirects and this does not preserve the original URL. What you need is an internal redirect.

You also need to use QSA flag to keep the query string, if needed. It's there by default. So:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^s/([a-zA-Z_-]+)$ /s/ [L]
</IfModule>

But there's probably a problem here; you're missing the passed data (eg united-states ). You probably want that to be mapped to your PHP script. To pass that as a querystring, you can do something like this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^s/([a-zA-Z_-]+)$ /s/?country=$1 [L,QSA]
</IfModule>

This way you're merging a new query string parameter ( country ) with all existing QS parameters, if any.

One more thing; you won't need a IndexIgnore * directive with Options -Indexes .

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