首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Yii 隱藏 URL 中 index.php 完整設定:urlManager 與 .htaccess 雙重配置

     編輯:PHP 綜合知識

兩步驟完成美觀網址

1. 設定 urlManager (config/main.php)

<?php
return [
    'components' => [
        'urlManager' => [
            'urlFormat' => 'path',        // 使用 PATH 格式 (非 GET 參數)
            'showScriptName' => false,    // 關鍵:隱藏 index.php
            'enablePrettyUrl' => true,    // 啟用美觀網址 (Yii 2.0+ 參數名)
            'rules' => [
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
                // 自訂規則範例
                'post/<id:\d+>' => 'post/view',
                'archive/<year:\d{4}>/<month:\d{2}>' => 'post/archive',
            ],
        ],
    ],
];
?>

2. 設定 Web 伺服器 Rewrite 規則

Apache (.htaccess 放於網站根目錄)

Options +FollowSymLinks
IndexIgnore */*

RewriteEngine on

# 真實存在的檔案/目錄直接存取
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# 其他請求導向 index.php
RewriteRule . index.php

Nginx (server 區塊內)

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

# 或舊版寫法
location / {
    if (!-f $request_filename) {
        rewrite ^/(.*)$ /index.php/$1 last;
    }
}

IIS (web.config)

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Yii2 Pretty URL" stopProcessing="true">
                    <match url="^(.*)$" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

驗證是否生效

原始網址美觀網址對應路由
`/index.php?r=site/index``/site/index` 或 `/``site/index`
`/index.php?r=post/view&id=123``/post/123``post/view`
`/index.php?r=user/profile&name=john``/user/profile/name/john``user/profile`

常見問題排查

  • 404 Not Found:Rewrite 模組未啟用、.htaccess 權限/位置錯誤、規則語法錯誤
  • 網址仍顯示 index.php:`showScriptName` 未設 `false`、快取未清除
  • CSS/JS/圖片 404:靜態資源被 Rewrite 導向 index.php,需確認 `RewriteCond !-f` 生效
  • 子目錄部署:`RewriteBase /subdir/` 或 Nginx `location /subdir/` 調整

進階:RESTful API 規則

<?php
'rules' => [
    // REST 風格
    ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
    // 或手動定義
    'POST users' => 'user/create',
    'GET users' => 'user/index',
    'GET users/' => 'user/view',
    'PUT users/' => 'user/update',
    'DELETE users/' => 'user/delete',
],
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved