Search code examples
php.htaccessmodx

After the redirect I get the page: Site 'xxx' has redirected too many times


This is essentially the same page, I just need to redirect from a url that uses the GET parameter to a url without this parameter.

RewriteCond %{QUERY_STRING} ^category=([^&]+)&key=news-category$
RewriteRule ^news/$ /news/%1/? [R=301,L]

Solution

  • RewriteCond %{QUERY_STRING} ^category=([^&]+)&key=news-category$
    RewriteRule ^news/$ /news/%1/? [R=301,L]
    

    This rule should only apply to direct requests from the client, not rewritten requests (by other rules) - which is probably what's causing the redirect loop. You need an additional condition (RewriteCond directive) on the above rule. For example:

    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    :
    

    This rule should also appear early on in the .htaccess file, before other rewrites.

    The REDIRECT_STATUS environment variable is empty on the initial request and set to 200 (as in "200 OK" HTTP status) after the later rewrite.

    Also, if you are on Apache 2.4, consider using the QSD (Query String Discard) instead of appending an empty query string (in order to remove the original query string). The QSD flag completely removes the query string, whereas the trailing ? sets an empty query string which relies on the user-agent (browser) removing the trailing ? in the redirected request.

    Clear your browser cache before testing and test with 302 (temp) redirects to avoid potential caching issues.

    Aside: Make sure you are linking directly to the "pretty" URL. This "redirect" directive should not be processed at all under normal conditions (it's only required to preserve SEO when changing an existing URL structure).