Reputation: 35
I want to have a formatted URL like this:
www.mysite.com/view.php?id=1
where:
"id" range: 1-99 (without leading "0" from 1 to 9)
"id": always lowercase, no "Id" or "ID" or "iD"
Anything different from this format must redirect it to
www.mysite.com/view.php or formatted ID
value:
Examples:
www.mysite.com/view.php?id=1sdeW --> www.mysite.com/view.php?id=1
www.mysite.com/view.php?erwrrw34 --> www.mysite.com/view.php
www.mysite.com/view.php?id=01 --> www.mysite.com/view.php?id=1
www.mysite.com/view.php?ID=33 --> www.mysite.com/view.php?id=33
I did some part of this logic already (RegExp, htaccess, rewriterules):
Please, help to complete the full logic above.
RewriteEngine On
RewriteCond %{QUERY_STRING} ID=([0-9]+)
RewriteRule ^(.*)$ /view.php?id=%1 [R=301,L]
I simplified my approach to achieve the same results:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/view.php$
RewriteCond %{QUERY_STRING} ^(?!(id=[1-9][0-9]{0,1})$).*$
RewriteRule .* ? [R=301,L]
1) With:
RewriteRule .* ? [R=301,L]
It works, but the link placed inside of my web page to:
www.mysite.com/view.php
also redirects to:
www.mysite.com
2) With:
RewriteRule .* /view.php? [R=301,L]
I receive well known "TOO MANY REDIRECTS" loop.
How do I get rid of this?
Upvotes: 2
Views: 110
Reputation: 5769
The main thing is to make sure that you handle only URLs that starts with /view.php
. Next, when you use RewriteRule
there is no need to capture the URL using ^(.*)$
. Finally, divide the logic into smaller handlers.
# Correct the wrong case for the "id" parameter
RewriteCond %{REQUEST_URI} ^/view.php$
RewriteCond %{QUERY_STRING} (ID|Id|iD)=(\d+)
RewriteRule . /view.php?id=%2 [R=301,L]
# Make sure that "id" contains only digits
RewriteCond %{REQUEST_URI} ^/view.php$
RewriteCond %{QUERY_STRING} id=([1-9]\d*)[^&]+
RewriteRule . /view.php?id=%1 [R=301,L]
# Check if the current URL contains "view.php?" but doesn’t have a valid "id" string
RewriteCond %{THE_REQUEST} ^[A-Z]+\s+/view.php\?
RewriteCond %{QUERY_STRING} !(id=[1-9])
RewriteRule . /view.php? [R=301,L]
Upvotes: 1