Intelligencia.UrlRewriter.dll を用いた URL リライトの実装手法

Intelligencia.UrlRewriter.dll を活用して、ASP.NET アプリケーション内で URL の見た目を静的ページ風に変換する方法を紹介します。

1. 必要な DLL の取得

まず、Intelligencia.UrlRewriter.dll を公式サイトまたは信頼できるソースからダウンロードします。

2. プロジェクトへの参照追加

ダウンロードした DLL をプロジェクトに参照として追加し、ビルド時に正しく読み込まれるように設定します。

3. Web.config の設定

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="urlRules" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
  </configSections>

  <urlRules>
    <rewrite url="~/(\w+)\.html$" to="~/Home.aspx?slug=$1" />
  </urlRules>

  <system.web>
    <httpModules>
      <add name="RewriteModule" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
    </httpModules>
  </system.web>
</configuration>

4. サンプルページの作成

Home.aspx(実際の処理を行うページ):

public partial class Home : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var slug = Request.QueryString["slug"];
        Response.Write($"リライトされたページ: {slug ?? "未指定"}");
    }
}

Navigate.aspx(リンクを提供するページ):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Navigate.aspx.cs" Inherits="WebApp.Navigate" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ナビゲーション</title>
</head>
<body>
    <form id="form1" runat="server">
        <a href="product.html">商品ページへ</a>
    </form>
</body>
</html>

5. 動作の仕組み

ユーザーが product.html にアクセスすると、内部では Home.aspx?slug=product が処理され、URL は変更されずに表示されます。

6. デフォルトドキュメントの再実装

ASP.NET が全リクエストを処理する場合、IIS のデフォルトドキュメント機能が無効になるため、以下のように明示的に定義します:

<rewrite url="^(.+)/?$" to="$1/index.aspx" />

複数のデフォルトファイルをサポートする場合は:

<if url="^(.+)/?$">
  <rewrite exists="$1/home.aspx" to="$1/home.aspx" />
  <rewrite exists="$1/start.aspx" to="$1/start.aspx" />
  <rewrite exists="$1/main.html" to="$1/main.html" />
</if>

7. 静的リソースの除外設定

CSS や画像などの静的ファイルは ASP.NET による処理をスキップさせる必要があります:

<rewrite 
  url="^/.+\.(css|js|png|jpg|gif|ico)(\?.*)?$" 
  to="$0" 
  processing="stop" />

8. 正規表現の活用ポイント

  • ^:URL の先頭を表す
  • $:URL の末尾を表す
  • ~/:アプリケーションの仮想ルートを指す(サブディレクトリ配置でも動作可能)

9. クエリストリングの柔軟な処理

パラメータを含む URL のリライト例:

<!-- クエリ文字列をそのまま引き継ぐ -->
<rewrite url="^~/item(\?.+)?$" to="~/Home.aspx$1" />

<!-- カスタムパラメータを追加 -->
<rewrite url="^~/shop(\?(.+))?$" to="~/Home.aspx?section=shop&amp;$2" />

タグ: ASP.NET URLリライト Intelligencia.UrlRewriter Web.config 正規表現

8月18日 21:50 投稿