skip to Main Content

I’m struggling to implement a conditional redirect.
All requests example.com/app/?s={some string} (and nothing else) should be redirected to example.com/?s={some string}.

I tried many things and looking up StackOverflow. My final draft was this:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^/app/?s=
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /?  [R=301]

But it didn’t work :-/ Any ideas?

UPDATE:

My approach now is

RewriteCond %{REQUEST_URI} ^/app/
RewriteCond %{QUERY_STRING} ^s=(.*)
RewriteRule (.*) /  [R=301,L]

Still not working 😀

UPDATE 2:

2

Answers


  1. The documentation tells us:

    Modifying the Query String

    By default, the query string is passed through unchanged

    However, you are explicitly setting it to be empty.

    Login or Signup to reply.
  2. All requests example.com/app/s={some string} should be redirected to example.com/s={some string}

    You have no ? in your example URLs, consequently there is no query string. s= is simply part of the URL-path (it’s not strictly a URL parameter). (This does, however, contradict your code sample where you are trying to match a ? and query string? It is this that I was trying to clarify in comments.)

    If s={some string} is really part of the URL-path then try the following instead:

    RewriteEngine On
    
    RewriteRule ^app/(s=.*) /$1 [R=302,L]
    

    UPDATE: I forgot the ? in the exaple above

    In that case your first “update” should have worked (depending on where you’ve put the directives). However, it would be better to write it like this:

    RewriteCond %{QUERY_STRING} ^s=
    RewriteRule ^app/$ / [R=302,L]
    

    It’s more efficient to check the URL-path in the RewriteRule pattern, since this is processed first. The query string is passed through by default (no need to capture {some string}).

    Test with 302 (temporary) redirects to avoid caching issues. Change to a 301 (permanent) – if that is the intention – only once you have confirmed it is working OK.

    You will need to clear your browser cache before testing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search