Django 1.3 URL重写

Django具有CommonMiddleware设置,默认情况下会在不以1结尾的URL后面加上斜杠.

例如:
(1)如果在URLconf中检测到/ admin /存在,则将http://www.example.com/admin重写为(2)http://www.example.com/admin/.

但是,我得到的情况不是(2),而是(3)http://www.example.com//admin/,这给了我404错误.

这是正确的行为吗?解决404错误的一种方法是什么?
非常感谢.

注意:
我正在Django 1.3 nginx gunicorn上运行.
我尝试使用Django 1.3 nginx apache mod_wsgi运行,我也得到了(3)(因此这不是网络服务器的问题),但没有得到404错误.

================================================== ====================

更新:

问题出在nginx配置上,我写了将HTTP请求重定向到HTTPS的配置.
以下是带有错误的nginx配置的示例:

upstream django {
    server 127.0.0.1:8000;
}

server {
    listen  80; 
    server_name www.example.com;

    location / { 
        rewrite (.*) https://www.example.com/$1 permanent;
    }   
}

server {
    listen       443;
    server_name  www.example.com;

    ssl                  on;
    ssl_certificate      /home/user/certs/example.com.chained.crt;
    ssl_certificate_key  /home/user/certs/example.com.key;
    ssl_prefer_server_ciphers on;

    ssl_session_timeout  5m;

    location ~ ^/static/(.*)${
        alias /home/user/deploy/static/$1;
        access_log off;
        expires max;
    }

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

    location @django_proxy {
        proxy_pass          http://django;
        proxy_redirect      off;    
        proxy_set_header    Host                 $host;          
        proxy_set_header    X-Real-IP            $remote_addr;   
        proxy_set_header    X-Forwarded-For      $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Protocol    https;  
    }
}

发生的是CommonMiddleware从https://www.example.com/admin重定向到http://www.example.com/admin/.再次击中nginx,并按照配置文件中的指定将URL重写为https://www.example.com/ $1,其中$1为“ / admin /”.这意味着最终的URL是https://www.example.com//admin/.

为了解决这个问题,我将重写规则更改为:

server {
    listen  80; 
    server_name www.example.com;

    location / { 
        rewrite /(.*) https://www.example.com/$1 permanent;
    }   
}
最佳答案
“这是正确的行为吗?”不,这不对.在使用Django的4年中,我从未见过这个特殊的问题.

测试CommonMiddleware导致这种情况的一种方法是在您的settings.py文件中将其注释掉,重新启动,然后查看是否出现相同的行为.使用独立的开发服务器并在有趣的地方粘贴指纹以查看谁在处理它也可能很有帮助.

相关文章

文章浏览阅读3.7k次,点赞2次,收藏5次。Nginx学习笔记一、N...
文章浏览阅读1.7w次,点赞14次,收藏61次。我们在使用容器的...
文章浏览阅读1.4k次。当用户在访问网站的过程中遇到404错误时...
文章浏览阅读2.7k次。docker 和 docker-compose 部署 nginx+...
文章浏览阅读1.3k次。5:再次启动nginx,可以正常启动,可以...
文章浏览阅读3.1w次,点赞105次,收藏182次。高性能:Nginx ...