简体   繁体   English

URL 的 htaccess 重写规则

[英]htaccess rewrite rule for URL

I want to have a formatted URL like this:我想要一个像这样格式化的 URL:

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:与此格式不同的任何内容都必须将其重定向到www.mysite.com/view.php或格式化的ID值:

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 ):我已经做了这个逻辑的一部分( RegExphtaccessrewriterules ):

Please, help to complete the full logic above.请帮助完成上面的完整逻辑。

RewriteEngine On
RewriteCond %{QUERY_STRING} ID=([0-9]+)
RewriteRule ^(.*)$ /view.php?id=%1 [R=301,L]

EDIT #1编辑#1

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: 1) 与:

   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: 2) 与:

   RewriteRule .* /view.php? [R=301,L]

I receive well known "TOO MANY REDIRECTS" loop.我收到众所周知的“太多重定向”循环。

How do I get rid of this?我该如何摆脱这个?

The main thing is to make sure that you handle only URLs that starts with /view.php .最重要的是确保您只处理以/view.php开头的 URL。 Next, when you use RewriteRule there is no need to capture the URL using ^(.*)$ .接下来,当您使用RewriteRule ,无需使用^(.*)$捕获 URL。 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM