从 URL 重写,不带尾部斜杠

从 URL 重写,不带尾部斜杠

我设置了 nginx,它可以很好地将请求重定向/files/到某个本地目录中的文件。唯一不起作用的是当人们点击时/files。当点击/files它根本不符合我的/files规则,最终被发送到代理转发部分,导致 Tomcat 出现 404。

所以我想要的是 1. 从 重定向/filesfiles/ 2. 重写请求到/files以便它们能够达到与 相同的规则/files/

server {
    listen 443 ssl;
    server_name ci.mycompany.com;
    client_max_body_size 10M;

    # keys are not checked into source control!
    ssl_certificate      ssl/wildcard.mycomp.com.signed.bundle.pem;
    ssl_certificate_key  ssl/wildcard.mycomp.com.key; 

    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;

    # file area where we can dump files from the build processes
    location /files {
        root /home/mycomp/ci-www-files; 

        # as 'root' directive works by appending the location to the 
        # root when resolving the url we need this voodoo to remove
        # the ^/files$ part of the url :(
        location ~ ^/files(.+)$ {
            root /home/mycomp/ci-www-files; 
            try_files $1 $1/ /index.html;
            autoindex on; # otherwise you would need the exact file name

            auth_basic "Semi-protected file sharing";
            auth_basic_user_file /etc/nginx/ci-www-files-htpasswd;
        }

        # This isn't working!
        location ~ ^/files$ {
            root /home/mycomp/ci-www-files; 
            try_files /files/ /files/index.html;
        }
    }

    location / {
        proxy_pass http://127.0.0.1:8111;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}

答案1

您应该使用alias。请参阅这个文件了解详情。

location /files {
    alias /home/mycomp/ci-www-files;         

    autoindex on;
    auth_basic "Semi-protected file sharing";
    auth_basic_user_file /etc/nginx/ci-www-files-htpasswd;
}

相关内容