nmax
nmax

Reputation: 1101

Use .htaccess to Clean URL and Rewrite Same Query, without "Too Many Redirects"

A user requests the following URI:

https://example.com/page.php?s=201903071830&e=201904192359&t=sampletitle

I want to use .htaccess to rewrite a clean URI in the browser:

https://example.com/sampletitle

And I want to map the clean URI back to the original URI.

I tried the following .htaccess rules:

RewriteCond %{QUERY_STRING} ^s=201903071830&e=201904192359&t=sampletitle$
RewriteRule (.*) https://example.com/sampletitle? [R,L]
RewriteRule ^sampletitle\/?$ /page.php?s=201903071830&e=201904192359&t=sampletitle [L]

Expecting that the [L] flag would stop rule-processing, here's what I thought would happen:

  1. User request original (complex) URI.
  2. .htaccess redirects to /sampletitle; rule processing ends.
  3. RewriteCond does not match, so first RewriteRule is skipped.
  4. Second RewriteRule matches and rewrites; rule processing ends.

But instead, I receive "ERR_TOO_MANY_REDIRECTS," presumably because .htaccess is stuck in rewrite-matching loop.

How can I use .htaccess to redirect incoming requests for the original URI and then rewrite the same query string?

Upvotes: 0

Views: 34

Answers (2)

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

Keep your rules as is and change the second line like this :

RewriteCond %{QUERY_STRING} ^s=201903071830&e=201904192359&t=sampletitle$
RewriteRule !^page\.php https://example.com/sampletitle? [R,L]
RewriteRule ^sampletitle\/?$ /page.php?s=201903071830&e=201904192359&t=sampletitle [L]

The error happened because you match against QUERY_STRING so , both URIs, original URI and the one you Rewrited to internally , have same QUERY_STRING but diffrent URI and that why you should exclud a URI start with page.php in this RewriteRule !^page\.php line.

Upvotes: 1

James Anderbard
James Anderbard

Reputation: 494

Edit, I see the issue with what I originally posted and what you're trying to do. Give this a go:

RewriteCond %{QUERY_STRING} ^s=201903071830&e=201904192359&t=sampletitle$
RewriteCond %{REQUEST_URI} !^\/?page.php
RewriteRule (.*) https://example.com/sampletitle? [R,L]
RewriteRule ^sampletitle\/?$ /page.php?s=201903071830&e=201904192359&t=sampletitle [L]

Upvotes: 1

Related Questions