加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > Nginx > 正文

在nginx上重写一个子目录到root

发布时间:2020-12-13 21:19:45 所属栏目:Nginx 来源:网络整理
导读:假设我有一个站点http:// domain /并且我将一些文件放在子目录/ html_root / app /中,并使用以下重写规则将此文件夹重写到我的root: location / { root /html_root; index index.php index.html index.htm; # Map http://domain/x to /app/x unless there

假设我有一个站点http:// domain /并且我将一些文件放在子目录/ html_root / app /中,并使用以下重写规则将此文件夹重写到我的root:

location / {
    root /html_root;
    index index.php index.html index.htm;

    # Map http://domain/x to /app/x unless there is a x in the web root.
    if (!-f $request_filename){
        set $to_root 1$to_root;
    }
    if (!-d $request_filename){
        set $to_root 2$to_root;
    }
    if ($uri !~ "app/"){
        set $to_root 3$to_root;
    }
    if ($to_root = "321"){
        rewrite ^/(.+)$/app/$1;
    }

    # Map http://domain/ to /app/.
    rewrite ^/$/app/ last;
}

我知道这不是一个聪明的方法因为我有另一个子目录/ html_root / blog /我希望它可以通过http:// domain / blog /访问.

我的问题是,上面的重写规则工作正常,但仍有一些问题:如果我访问

http:// domain / a-simple-page /(它从http:// domain / app / a-simple-page /重写)

它工作正常,但如果我访问

http:// domain / a-simple-page(不带斜杠),重定向到原始地址:

HTTP://网域/应用/ A-简单页/,

任何方式重定向URL而不用尾随斜杠遵循我的规则?

最佳答案
遵循右下错误教程而非reading the wiki的经典案例我强烈建议您阅读有关您(应该)使用的功能(例如location和try_files)以及my Nginx primer,因为您完全错过了Nginx的基础知识.

我试图用正确的格式写出你想要的东西,但我不能保证它会起作用,因为我不确定我真的明白你要做什么,不过,它应该给你一个基础从一开始.

server {
    listen 80;
    server_name foobar;

    root /html_root;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ @missing;
    }

    location /app {
        # Do whatever here or leave empty
    }

    location @missing {
        rewrite ^ /app$request_uri?;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读