Sicyinuavien '“Chuyên trang dành cho kỹ thuật viên tin hoc" CHIA SE - KINH NGHIỆM - HỌC TẬP - THỦ THUẬT IIS Web Server - Part 5 - URL Rewrite in IIS7 with URL Rewrite Module Giới thiệ
Trang 1Sicyinuavien '“Chuyên trang dành cho kỹ thuật viên tin hoc"
CHIA SE - KINH NGHIỆM - HỌC TẬP - THỦ THUẬT
IIS Web Server - Part 5 - URL Rewrite in IIS7 with URL Rewrite Module
Giới thiệu:
Microsoft URL Rewrite cho IIS 7.0 cung cấp những quy tắc linh hoạt nhằm viết lại những liên kết của website theo một dang khác mà vẫn đảm bảo đúng nội dung liên kết đó
* Việc viết lại URL được dựa vào HTTP headers và server variables
* Nội dụng trang web
* Sự truy nhập tới nội dụng trang web cần kiểm soát
Download Module
Download the x86 CTP version for IIS 7.0: http://www.iis.net/downloads/default.aspx ?tabid= 34 &g=6 &i= 1691
Download the x64 CTP version for IIS 7.0: http://www.iis.net/downloads/ default.aspx ?tabid= 34 &g=6 &i= 1692
Để sử dụng được URL Rewrite bạn cần chuẩn bị đủ các yêu cầu sau:
1 IIS 7.0 & ASP.NET phải được enabled;
2 URL rewrite module phải được cài đặt
1 Khởi tạo và chạy thử URL Rewrite
Để sử dụng URL Rewrite tôi sẽ sử dụng một ví dụ với một trang web ASP.Net Trang web này sẽ chạy trên server variables và trích xuất kết quả của chúng ra trình duyệt
Copy toàn bộ nội dung trang ASP.NET vào thư mục %SystemDrive%\inetpub\wwwroot\ và file ví dụ trong bài này là article.aspx:
“ article.aspx - Microsoft Visual Studio (Administrator) ©) ||memi
File Edit View Project Debug Data Format Tools Test Analyze Window Help
aO@ea- Aa |*sEBAl ALS S/9-C- 2-3 > un go š(5°:|AJ#za s
: Style Application: Manual + Target Rule: (New Inline Style) x lat? | Tay] Ề
& <html xmlins="Hnttp://www.w3.ore/1999/xhtmi">
<meta http-equiv="Content-Type" content=a"texafatml; charset=utf-8" />
<hi>URL Rewrite Module Test Pag¢%/hi>
<tr> `
<th>Server a
ae
</tr>
<tr>
<td>Original URL: </td>
<td>< %= Request ServerVariables[("HITP_X ORIGINAL URL") %></t
</tr>
<tr>
<td>Final URL: </td>
<td>< = Request ServerVariables["PATH_INFO"] + "2?" + Request v
tả Design | CO Split | & Source | [4|[<htm> |[<body>| I
Nội dung đoạn Code:
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="http://www.w3.org/1999/xhtm1">
<head>
<meta http-equiv="Content-Type" content="text/html;
<title>URL Rewrite Module Test</title>
</head>
<body>
<h1>URL Rewrite Module Test Page</h1>
<table>
<tr>
"http://www.w3.org/TR/xhtml1/DTD/xhtmll-transitional.dtd">
charset=utf-8" />
<th>Server Variable</th>
<th>Value</th>
</tr>
<tr>
<td>Original URL: </td>
1 of 9
Trang 2</tr>
<tr>
<td>Final URL: </td>
<td>< %= Request.ServerVariables["PATH_INFO"] + "?" + Request.ServerVariables["QUERY_STRING"] %></td>
</tr>
</table>
</body>
</html>
Sau khi copy xong ban vao http://localhost/article.aspx để test thử
/> URL Rewrite Module Test - Windows Internet i - (oO) x|
‹c>t»* B http://localhost/article.aspx xị +llX |Lxe Search Pir
we ae @€ ) URL Rewrite Module Test | | fp + + ta v :}Page x (7Tools ~ =
El URL Rewrite Module Test Page
Server Variable Value aS
Original URL: c°
Einal URL: /article.aspx? ©
li
[Done [ [ [ [ [ [ «Sy [Rk Locaalintranet | Protected Mode: Off *100% v 4
2 Tién hanh URL Rewrite
Trong bài này tôi sẽ hướng dẫn bạn Rewrite một link đại khái như các trang Vnexpress.net , Vietnamnet.vn có dạng như bên dưới:
http://localhost/article/342/some-article-title
sẽ được hiểu như link:
http://localhost/ article.aspx ?id= 342&†itle= some-article-title
Chung ta sé str dung URL Rewrite UI trong 1IS Manager Bạn làm theo các bước:
1 Vao IIS Manager
2 Chon "Default Web Site"
3 Trong Feature View chon "URL Rewrite Module"
2 of 9
Trang 3rae»
—
File View Help
@- i |4 |B
-@4 Start Page
3 BAONGUYEN-PC (BaoNgu
ị - Application Pools
4 -ểi Site:
‘AQ Default Web Site
|@ » BAONGUYEN-PC > Sites » Default Web Site > “
` Default Web Site Home
Filter: + GQGo ~GyShow All | Group by:
CGI
L 6
Authentic Compresito Default
Document
+
Directory DynamicIP ErrorP., Handler HTTP Browsing Address a > Mappings — Respon
sư
Loggi MIME Types Modules Output
Caching ISAPI Filters
cr AP
OF
Request
Management
= “ ,
Open Feature Explore Edit Permissions
Edit Site
Bindings
Basic Settings
View Applications View Virtual Directories
Manage Web Site
Restart Start Stop Browse Web Site Browse *:80 (http) Advanced Settings
Configure
Limits
Add FTP Publishing
Help Online Help
©
File View Help
- GY Start Page
4-83 BAONGUYEN-PC (BaoNgu
ị sy @ Application Pools
4-8) Sites
Q3 URL Rewrite
Provides URL rewriting capabilities based on rules
Inbound Rules that are applied to the requested URL string:
Name Action Type ta ction URL
Outbound Rules về applied to the content of HTTP response:
Name Pre-condition Tag Filters
Revert To
Manage Rewrite Maps
View Rewrite Maps
Inbound Rules
Import Rules
Outbound Rules + View Pre-conditions
aren
View Custom Tags
@ Halp Online Help
Configuration: 'Default Web Site' web.config
Đến đây ta có 2 cách để Rew rite một trang Web:
Cách 1: chọn User friendly URL
3of9
Trang 4
Inbound rules
Blankrule |Userfriendly| Rule with Request XS
Select this rule template to create rules for enabling user friendly URLs for your dynamic web applications The template
generates rules for rewriting user friendly URLs to internal URLs that your web application understands
| OK | | Cancel
Sau đó nhập chuỗi article.aspx?id=123&title=abc vao 6 friendly URLs
Chú ý là 123 sẽ đại diện cho các Request là số còn abc là đại điện cho các Request là chữ và bạn có thể thay thế 123 bằng con số bất kỳ và tương tự với abc bạn có thể thay thế abc bằng một chuỗi ký tự bất kỳ
article.aspx?ID=123 &title= abc
ault.aspx?c=hiking&p=boots Select an example of corresponding public URL that you want your web site visitors to see
browsers:
Rewrite rule definition
^article/([^/]+)/([^/]+)/?S CG
Substitution URL: =` $
=-
Create corresponding redirect rule
This will generate a redirect rule to reciprocate the rewrite rule, so that clients using the
internal URL will be redirected to the friendly URL and see that in the browser
| OK | | Cancel
Tai 6 Select an example ban chon dang Rewrite la article/123/abc/ sau dé nhdp OK
Một Rules mdi dudc tao trong bang URL Rewrite
4 of 9
Trang 53) ) |@ > BAONGUYEN-PC > Sites » Default Web Site >
eee
File View Help
Qà URL Rewrite
@- 14 |B
~~ G4 Start Page
4 a3 BAONGUYEN-PC (BaoNgu
ị - @ Application Pools
°
Provides URL rewriting capabilities based on rules
Inbound Rules that are applied to the requested URL string:
Action Type RewriteUserFriendlyURL1 Rewrite
&
G
Outbound Rules that are’applied te the content of HTTP response:
Add Rules
Revert To Parent Manage Rewrite Maps View Rewrite Maps
cСcn URL 4S Srticle.aspxiID=(Rrljewi || Inbound Rules aA
Rename
X Remove Disable Rule
# Move Up
@ Move Down Import Rules
View Pre-conditions
Stop Proce Entry
View Custom Tags
@ Help
(3 Content View Configuration: ‘Default Web Site’ web.config
Nhấp vào Edit Rule ta sẽ thấy chỉ tiết các giá trị của Rule này và bạn có thể tùy chỉnh lại các giá trị này
Q3 Edit Rule
Name:
| RewriteUserFriendlyURL1 |
Pattern:
Conditions
Logical Grouping:
Track capture groups across conditions
Action
ews 3 &
(Regular Expressions |
[ Test pattern 3
article.aspx?7ID={R:1}&ttitle={R:2}
Append query string RY
Stop processing of subsequent rules
Trở lại thư mục Web bạn sẽ thấy Windows sẽ tự tạo ra một file web.config mới với nội dung là các ham URL Rewrite tudng ứng
5 of 9
Trang 6
Ov -[i >» Computer » DATA(D:) >» Website
Organizex @@Open v Bum Newfolder
WY Favorites 3] article
WH Desktop fy web
B Downloads
Ge =| Recent Places
Pd web - Ï ote F
File Edit Format View Help c
EN Libraries
BẦ Documents
k?xml version="1.0" encoding="UTF-
<system webSer ver> &
<rules>
(eS) Pictures <rule na Gdewr iteuserFriend1yURLL" atter nsyntax="EC
B Videos <ma ar ]="Aarti cle/(C[A/14)//C[A/1+)/?$" ignorecas
<co jons logicalGrouping="MatchaAll]" trackATTcap
“<add input="{REQUEST_FILENAME }" mat chType="IsF
& Windows 7 (C;) SS acti on type="Rewrite” url="article aspx?ID={R:1}é
cx CD Drive (F:) </system webServer>
<system web>
<compilation defaultLanguage="c#" />
</system web>
</configuration>
Bây giờ bạn restart lại Web Server và vào lại localhost để test xem nhé:
[6A1 1 Rewrite Module v2 Test - Windows Internet Explorer
we oe (@ URL Rewrite Module v2 Test | |
\é) http: /flocalhost/article/342/some-article-title p | v |
liền + deb v : È Page v Gj Tools ~ ”
zl
URL Rewrite Module v2 Test Page
‹°
RS
©
Inbound URL Rewriting
Onginal URL: = /article/342/some-article-ttle ©
Final URL: farticle.aspx?id=34 2 &ttle=s Tu,
Outbound URL Rewriting
Here is link to this article
⁄ a
fattp: {localhost/article/342/some-article-tit iE [ [ = im [ ee Local intranet | Protected Mode: Off
Cach 2: chon Blank rule
| 100% x
6 of 9
Trang 7
Inbound rules
Blankrule | Userfriendly Rule with Request XS
URL rewrite map blocking &
Select this rule template to create a new inbound rule from scratch The template opens the “Edit Rule” user interface that
can be used for defining new rewrite rule for changing the requested URL string
| OK | Cancel
Dat tén cho Rule la Rewrite to article.aspx
Trong ô "Pattern" bạn nhập vào chuỗi sau:
^article/([0-9]+) /([_0-9a-z-]1)
Chuỗi này là một biểu thức bình thường mà chỉ rõ rằng mẫu sẽ phù hợp với bất kỳ chuỗi URL nào mà gặp những điều kiện sau đây
1 Bắt đầu với chuỗi có đặc tính là "article/"
2 Chứa đựng một hoặc nhiều ký tự số sau dấu "/" đầu tiên
3 Chứa đựng một hoặc nhiều chữ số hay dấu "_ " hay dấu "-" sau dấu "/"
3 Định nghĩa sự hoạt động:
Một khi qui tắc mà bạn tạo ra để viết lại URL của một file ASP.net nào đó phải tương ứng với những gì mà bạn định nghĩa cho file ASP.Net đó trong
mục Action, Chọn mục "Rewrite" trong mục "Action"” Trong ô "Rewrite URL:" nhập chuỗi sau:
article.aspx?id={R:l}&title={R:2}
Q3 Edit Rule
Name:
Rewrite to article.aspx
Match URL
Pattern:
“
Action Type:
Action properties
Rewrite URL:
article.aspx?id={R:1}&ttitle={R:2|}
Append query string
Sau đó nhấp "Apply" và lưu công việc của bạn lại
Bây giờ bạn restart lại Web Server và vào lại localhost để test xem nhé:
7 of 9
Trang 8
Go \é) http: /flocalhost/article/342/some-article-title xị | +|| < |Lxe Search 2 lá
we abe @ur Rewrite Module v2 Test | | fy Y v fn x (::} Page x @ Tools v tet
=|
URL Rewrite Module v2 Test Page
© Inbound URL Rewriting œ®
Onginal URL: /aricle/342/sorne-arhcle-tilE ©
Final URL: farticle.aspx?1d=34 2 &title=s Die tie
Outbound URL Rewriting
Here is link to this article
ttp:/{localhostfarticle/342/some-article-tit 1 [ [ i in = a Local intranet | Protected Mode: OFf '%® 10109
4 Sử dụng URL Rewrite Redirect:
Với cách này bạn có thể dễ dàng chuyển trang bằng URL Rewrite như ví dụ bên dưới
http://localhost/blog/some-other-title/543
sẽ được chuyển đến:
http://localhost/ article/543/som e-other -title
Cách cấu hình cũng tương tự như trên nhưng có một số thay đổi khác chút:
e Ô Name bạn nhập: "Redirect from blog"
® Ó Pattern nhập: ”^ blog/ ([_0-9a-z-]+)/([0-9]+)"
® Mục Action chọn là: "Redirect"
® Ô Redirect URL nhập là: "article/ {R:2}/{R:1}"
Lưu ý là trong phần này ta đã chuyển đổi R:1 & R:2 hoán đổi vị trí cho nhau rồi
Q3 Edit Rule
Name:
Redirect from Blog
Match URL
“blog/([_0-9a-z-]+)}/([0-9]+)
@
Action Type:
Action properties
Redirect type:
article/{R:2}/{R:1}
Append query string
Redirect URL:
Bây giờ bạn vào Web Browser nhập
8 of 9
x
ay
Trang 9Bạn thấy nó sẽ chuyển đến trang
http://localhost/ article/ 323/som e-other -title
ŸURL Rewrite Module v2 Test - Windows Internet Explorer
w & URL Rewrite Module v2 Test | | đà + E] r asp + [ib Page ~ Gi Tools ~ ”
URL Rewrite Module v2 Test Page
©
Qo
FS
|£› http: /flocalhost/article/342/some-article-title *| >| x |Lxe Search
Inbound URL Rewriting
Onginal URL: /arhcle/342/sorae-arhcle-tilE
Final URL: article aspx id=34 2tntles / gor 1cle-title
Outbound URL Rewriting
Here is link to this article
ttp:/{localhostfarticle/342/some-article-tit Ƒ [ _ [ = [ = @ Local intranet | Protected Mode: OFf H1i00% v ⁄
5 Ngăn chặn sự truy cập trực tiếp:
Quy tắc thứ ba mà chúng tôi giới thiệu đến bạn được dùng để ngăn chặn mọi yêu cầu tới trang web nếu những yêu cầu đó không có định nghĩa trong URL Rewrite Kiểu quy tắc này hữu Ích khi bạn muốn ngăn ngừa những sự nỗ lực của hacker muốn tìm cách truy cập trực tiếp file nhằm khai thác lỗi SQL Injection
Md file web.config chén thêm các đoạn code sau vào:
<rule name="Fail bad requests">
<match url="."/>
<conditions>
<add input="{HTTP_HOST}" pattern="localhost" negate="true" />
</conditions>
<action type="AbortRequest" />
</rule>
Bạn cần phải viết lại như sau:
<rewrite>
<rules>
<rule name="Fail bad requests">
<match url="."/>
<conditions>
<add input="{HTTP_HOST}" pattern="localhost" negate="true" />
</conditions>
<action type="AbortRequest" />
</rule>
<rule name="Redirect from blog">
<match url="“*blog/ ([_0-9a-z-]+)/([0-9]+)" />
<action type="Redirect"™ url="article/{R:2}/{R:1}" redirectType="Found" />
</rule>
<rule name="Rewrite to article.aspx">
<match url="^article/([0-9]1)/([ 0-9a-z-]+)" />
<action type="Rewrite" url="article.aspx?id={(R:1}&title=(R:2}" />
</rule>
</rules>
</rewrite>
Kết luận
Trong bài viết này hy vọng bạn đã hiểu để định hình được URL Rewrite có những quy tắc nào và áp dụng chúng ra sao, bằng cách sử dụng IIS Manager của windows hay bằng việc bằng tay soạn thảo như thế nào trong file web.config
Chúc bạn thành công!
OK mình vừa trình bày xong phần URL Rewrite trong IIS7 vdi URL Rewrite Module
Công ty TNHH đầu tư phát triển tin học GC Com
Chuyên trang kỹ thuật máy vi tính cho kỹ thuật viên tin học Điện thoại: (073) - 3.511.373 - 6.274.294
Website: http://www.gccom.net
9 of 9