yii2设置伪静态

Apache服务器的配置

修改httpd.conf配置文件

  1. 将LoadModule rewrite_module modules/mod_rewrite.so前面的注释#号去掉。
  2. 添加如下内容
<Directory "path/to/basic/web">
    # use mod_rewrite for pretty URL support
    RewriteEngine on
    # If a directory or a file exists, use the request directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # Otherwise forward the request to index.php
    RewriteRule . index.php

    # ...other settings...
</Directory>

注意其中的path/to/basic/web修改成你的根目录,最后不要忘记重启apache服务器。

Nginx服务器的配置

修改nginx.conf配置文件,在域名对应的server{}内添加如下内容

location / {
    # Redirect everything that isn't a real file to index.php
    try_files $uri $uri/ /index.php$is_args$args;
}

最后不要忘记重载配置文件。

yii2代码的配置

修改config/web.php,在components数组中添加如下内容(去掉前后的注释)

'components' => [
    ...
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
        ],
    ],
    ...
],

这时再刷新网页,就能看到连接的形式发生了改变。此时默认会将/index.php?r=controller/action这样的形式修改为/controller/action(如果含有参数,则将/index.php?r=controller/action&...改为/controller/action?...)。

为了更好的将链接个性化配置,可以参照如下例子,在rules这个空的数组中添加相应的内容。

  • 文章列表

/index.php?r=post/index

添加'post'=>'post/index'

  • 通过id查看文章

/index.php?r=post/view&id=123

添加'post/<id:\d+>'=>'post/view'

其中\d+等价于[0-9]+

  • 通过标题查看文章

/index.php?r=post/view&title=hello-world

添加'post/<title:\w+>'=>'post/view'

其中\w+等价于[A-Za-z0-9_]+




最后config/web.php可能如下所示

'components' => [
    ...
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            'post'=>'post/index',
            'post/<id:\d+>'=>'post/view',
        ],
    ],
    ...
],

参考:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值