[分享] Laravel 的 Nginx 重写规则

文档那个上面比较简略,只有:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

您可以加上这些,让你的链接更加优雅

# 去除末尾的斜杠,SEO更加友好
if (!-d $request_filename)
{
    rewrite ^/(.+)/$ /$1 permanent;
}

# 去除index action
if ($request_uri ~* index/?$)
{
    rewrite ^/(.*)/index/?$ /$1 permanent;
}

# 根据laravel规则进行url重写
if (!-e $request_filename)
{
    rewrite ^/(.*)$ /index.php?/$1 last;
    break;
}
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   html;
}
本帖已被设为精华帖!
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2
Summer

很不错的代码小片段. :+1:

9年前 评论

你好,使用了你的代码在nginx中,发现基本上所有的接口是可以被访问的,但是对于有一些请求在nginx日志中存在301错误,但是只使用下面部分代码,接口可以完全被使用

        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }

        # 根据laravel规则进行url重写
        if (!-e $request_filename)
        {
            rewrite ^/(.*)$ /index.php?/$1 last;
            break;
        }
                error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!