nginx/docker-nginx

CSS Recognized as `text/html` and Not Served

Closed this issue · 1 comments

Describe the bug

I created a simple static website (index.html + styles.css) on my local host but found the CSS file was recognized as text/html instead of expected text/css. I am not sure whether I encountered the same cases as these.

To reproduce

Steps to reproduce the behavior:

  1. Create a simple website that only contains a simple index.html with an attached styles.css.
.
├── Dockerfile
├── html/
│   ├── index.html
│   └── styles.css
└── nginx.conf
# ./Dockerfile
FROM nginx

# Copy configuration and HTML files
COPY nginx.conf /etc/nginx/nginx.conf
COPY html/ /usr/share/nginx/html/

# Expose port 80
EXPOSE 80

# Start Nginx and keep it running
CMD ["nginx", "-g", "daemon off;"]
# ./nginx.conf
http {
    # FIXME: Nginx can't serve CSS files integrated in HTML files
    include mime.types;
    server {
        server_name localhost;
        listen 80;
        root /usr/share/nginx/html;

        location / {
            try_files $uri/index.html =404;
        }
    }
}

events {}
<!-- ./html/index.html -->
<html>
  <head>
    <link rel="stylesheet" href="./styles.css" />
  </head>
  <body>
    <h1>Hello, Nginx!</h1>
  </body>
</html>
/* ./html/styles.css */
html {
    color: white;
    background-color: green;
}
  1. Run Docker commands as follows:
docker build -t nginx-backend .
docker run -p 8000:80 nginx-backend
  1. Open localhost:8000 in the browser.
  2. You may notice CSS is not applied, and styles.css was recognized as text/html with a 404 HTTP status code in Developer Tools (F12) > Network:
HTTP/1.1 404 Not Found
Server: nginx/1.27.3
Date: Wed, 05 Feb 2025 02:29:17 GMT
Content-Type: text/html
Content-Length: 555
Connection: keep-alive

Expected behavior

CSS should be recognized as text/css and applied on HTML.

Your environment

  • Version/release of Docker and method of installation: Docker Desktop v4.37.1
  • Version/tag of the NGINX Docker image: nginx
  • Target deployment platform: N/A

Additional context

Add any other context about the problem here.

Hi @mr-yifeiwang !

The issue is in try_files - you're instructing nginx to try $uri/index.html for any request, and if that fails, to serve a 404.

You should probably drop it altogether.