Django 1.3 URL rewriting
Django has CommonMiddleware setup, which by default appends a slash to URLs that do not end with one.
For example: (1) http://www.example.com/admin is rewritten to (2) http://www.example.com/admin/ if it detects in the URLconf that /admin/ exists.
However, I am getting the situation where instead of (2), I am getting (3) http://www.example.com//admin/ which gives me a 404 error.
Is this correct behaviour? What would be one way to resolve the 404 error? Thanks a lot.
Note: I am running on Django 1.3 + nginx + gunicorn. I've tried running with Django 1.3 + nginx + apache + mod_wsgi and I'm getting (3) as well (so it's not a webserver problem) but I don't get the 404 error.
======================================================================
UPDATE:
The problem is with the nginx configuration, which I wrote to redirect HTTP requests to HTTPS. The following is a sample of the nginx configuration with the error:
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;
}
}
What was happening was the CommonMiddleware was redirecting from https://www.example.com/admin to http://www.example.com/admin/. This hit nginx again, and a URL rewrite was done as specified in the config file to https://www.example.com/$1 where $1 is "/admin/". This meant that the final URL was https://www.example.com//admin/.
To correct this, I changed the rewrite rule to:
server {
listen 80;
server_name www.example.com;
location / {
rewrite /(.*) https://www.example.com/$1 permanent;
}
}
"Is this correct behavior?" No, it's not. In 4 years of Djangoing I've never seen this particular problem.
One way of testing that the CommonMiddleware is causing this is to comment it out in your settings.py
file, restart, and then see if you get the same behavior. It can also be instructive to use the standalone development server and stick print
's in interesting places to see who is mangling it.
Check your URL's. You most likely have defined your URL's a bit incorrectly. If you have
(r'^admin', include(admin.site.urls))
instead of the correct
(r'^admin/', include(admin.site.urls)),
You will see this type of 404 with the middleware
精彩评论