Santhosh
Santhosh

Reputation: 11834

django: nginx: HTTP_HOST does not show port number

I have the following code running in production

The Nginx config is as follows:

# first we declare our upstream server, which is our Gunicorn application
upstream hello_server {
    # docker will automatically resolve this to the correct address
    # because we use the same name as the service: "djangoapp"
    server webapp:8888;
}

# now we declare our main server

server {

    listen 8558;
    server_name localhost;

    location / {
        # everything is passed to Gunicorn
        proxy_pass http://hello_server;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

Nginx server has port forwarding: 8555:8558

And the gunicorn command running is

gunicorn --bind :8888 basic_django.wsgi:application

Now in my browser i open this url:

http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email

Now my code in one of my views is

prev_url = request.META['HTTP_REFERER']
# EG: prev_url = http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email

# we want to get the url from namespace . We use reverse. But this give relative url not the full url with domain
login_form_email_url_reverse = reverse("login_register_password_namespace:user_login_via_otp_form_email")
# EG: login_form_email_url_reverse = "/login_register_password/user_login_via_otp_form_email"

# to get the full url we have to use do the below
login_form_email_url_reverse_full = request.build_absolute_uri(login_form_email_url_reverse)
# EG: login_form_email_url_reverse_full = "http://127.0.0.1/login_register_password/user_login_via_otp_form_email"

I am execpting prev_url and login_form_email_url_reverse_full to be same but it differs

prev_url domain is http://127.0.0.1:8555 whereas login_form_email_url_reverse_full domain is http://127.0.0.1

why this is happening.

This does not happen in development server. using runserver

"HTTP_HOST": "127.0.0.1:8555",
"HTTP_REFERER": "http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email",

Where as with nginx server: HTTP_HOST changes i.e now without port number

"HTTP_HOST": "127.0.0.1",
"HTTP_REFERER": "http://127.0.0.1:8555/login_register_password/user_login_via_otp_form_email",

Upvotes: 1

Views: 771

Answers (1)

Santhosh
Santhosh

Reputation: 11834

I solved the problem by changing

    proxy_set_header Host $host;

To

    proxy_set_header Host $http_host;

in the server {} of local.conf of nginx

Got the answer from https://serverfault.com/a/916736/565479

Upvotes: 3

Related Questions