大网数据广告活动
服务器运维问答

Rewrite from url without trailing slash

· 52CE 我爱测

I have nginx setup that works pretty fine redirecting requests hitting /files/ to files in some local directory. The only thing that isn't working is when people hit /files . When hitting /files it isn't matched by my /files rule…

问题原文

原帖链接 · oligofren · CC BY-SA 4.0

I have nginx setup that works pretty fine redirecting requests hitting /files/ to files in some local directory. The only thing that isn't working is when people hit /files. When hitting /files it isn't matched by my /files rule at all, and ends up being sent to the proxy forwarding section, resulting in a 404 from Tomcat.

So what I want is either 1. A redirect from /files to files/ 2. Rewriting requests to /files so they will hit the same rules as for /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;
    }
}

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

You should use alias. See this document for details.

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;
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-03-26)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。