Nginx: Docker Redirect

Spin off a new Nginx container in docker.

docker run --name nginx-web1 -p 8080:80 nginx

Go in side the newly created container.

docker exec -it nginx-web1 /bin/bash

Create some folders and files inside the root of http.

cd /usr/share/nginx/html
mkdir -p foo/bar
echo "<h1>Folder: /foo/bar/ File: index.html</h1>" > index.html

We will get something like this:

.
|-- 50x.html
|-- foo
|   `-- bar
|       `-- index.html
`-- index.html

Now see what happens if we try to go to this url:

curl localhost:8080/foo/bar
*   Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /foo/bar HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.85.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.23.2
< Date: Tue, 22 Nov 2022 08:22:47 GMT
< Content-Type: text/html
< Content-Length: 169
< Location: http://localhost/foo/bar/
< Connection: keep-alive
<
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.23.2</center>
</body>
</html>
* Connection #0 to host localhost left intact

You can see on line 14 above that it redirect our request to:

Location: http://localhost/foo/bar/

And when our browser follows to that location, it will complain because there are no service at localhost port 80.

curl -L localhost:8080/foo/bar
curl: (7) Failed to connect to localhost port 80 after 0 ms: Connection refused

To fix this we need to add one directive in our config.

absolute_redirect off;
Syntax:absolute_redirect on | off;
Default:absolute_redirect on;
Context:httpserverlocation

This directive appeared in version 1.11.8.

If disabled, redirects issued by nginx will be relative.

See also server_name_in_redirect and port_in_redirect directives.

Now when you try to visit the url:

curl localhost:8080/foo/bar
*   Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /foo/bar HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.85.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.23.2
< Date: Tue, 22 Nov 2022 09:06:39 GMT
< Content-Type: text/html
< Content-Length: 169
< Connection: keep-alive
< Location: /foo/bar/
<
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.23.2</center>
</body>
</html>
* Connection #0 to host localhost left intact

The Location header on line 15 show relative path which interpreted to browser as localhost:8080/foo/bar/.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *