I'm configuring nginx to load only static files and I don't know why .css files are interpreted as text/plain - finally browser couldn't load it.
Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:13000/styles.css".
when I check response header in web browser of css file:
Content-Type: text/plain
I know that on stack we have a lot of issues with it, I've already read them but still doesn't work.
in html file I've just import css:
<link href="styles.css" rel="stylesheet" type="text/css"/>
my /etc/nginx/nginx.conf is:
worker_processes 1;
events {
worker_connections 512;
}
http {
server {
listen 80;
server_name 0.0.0.0:80;
include /etc/nginx/mime.types;
root /project/app;
location ~* ^.+\.(js|css)$ {
expires 10d;
}
}
}
I tried without any location part or tried with:
location ~ \.css {
add_header Content-Type text/css;
}
In some responses in other threads I saw that this part is required:
default_type application/octet-stream;
include /etc/nginx/mime.types;
I added it in http part and after that in server and then in location, still didn't help me.
Is there anything else what can I do to fix it?
Just in case somebody has the same problem and use docker.
This is key word - I use docker with image nginx:latest which causes problems, I've changed it to nginx:1.14.2 and everything is working fine.
in html, import css:
<link href="styles/styles.css" rel="stylesheet" type="text/css"/>
my nginx.conf configuration:
worker_processes 1;
events {
worker_connections 512;
}
http {
include mime.types;
sendfile on;
server {
listen 80;
server_name 0.0.0.0:80;
root /project/app;
}
}
I solved the issue for myself. The problem on my side was the actual nginx configuration, let me explain.
Not working (before):
my dockerfile contained this line of code: "COPY deployment/nginx.conf /etc/nginx/nginx.conf"
my nginx.conf contained the "http {" part
How I fixed it:
I updated my docker file to: "COPY deployment/nginx.conf /etc/nginx/conf.d/default.conf" (check the new path where I am copying)
my nginx.conf did not contain any more "http {" block and just the "server {" block. (This works because I am adding a new config file).
Voila! Hope it helps! All in all the culprit was where I was copying the config file and the content of my conf file itself.
I had a similar issue once on my testing server. what i found out was that nginx was doing every thing in the right way. The problem was the referencing of the files. The browser could find the resources but could not load them from the described base.
location / { # default base
root /var/www/html/myfiles; # my root folder
try_files $uri /index.html;
include /etc/nginx/mime.types;
}
changed the base to...
location /myfiles { # changed base
root /var/www/html; # default root folder
try_files $uri /index.html;
include /etc/nginx/mime.types;
}
it worked seamlessly
I had this problem.
In order to solve it for both my static javascript and css files was to add type AND uic-remove as followed:
<link rel="stylesheet" uic-remove href="/index.css" type="text/css">
<script uic-remove type="application/javascript" src="./index.js"></script>
Note: The Javascript link was not throwing any warning or error like the css's warning, however it was nonetheless not working either and I thank the heavens that the fix worked for both. Good Luck!
Related
My setup:
One Docker container with nginx providing an Angular web-app.
One deployment, one service (LoadBalancer) in K8s (Docker Desktop).
nginx.conf
load_module modules/ngx_http_subs_filter_module.so;
http {
include /etc/nginx/mime.types;
server_tokens off;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
}
mime.types contains a huge list of mime types.
When I access the service with my browser I get
where all the mime types are set to text/html. (The browser blocks loading the js and css. "wrong mime type")
I work's without errors locally and on an AKS cluster.
How can I fix it and get the proper mime types?
Update:
I did some more debugging and found out that the mime types are even wrong when I connect to the nginx-container and call the site with curl. Therefore it must be an nginx issue. 🤔
Sorry, my fault!
Wrong configuration because of missing ingress on local (Docker Desktop) setup.
On my AKS system I have an additional ingress which rewrites the URL (removes a part).
The URL of the resources above where like localhost/portal/env.js
These localhost/portal URLS were redirected to index.html.
All the CSS and JS files just contained the index.html and therefore had the proper mime type.
I just needed to add an rewrite to my nginx.conf to fix the issue:
location /portal/ {
rewrite ^/portal/(.*)$ /$1 break;
}
I'm creating a Nginx file server, and I'm trying to enable the fancy-index module to get have custom header and footer, but I can't get it working, the header/footer never load. (The request isn't even done from the browser).
For now, I've followed this tutorial : https://neilmenon.com/blog/install-nginx-fancyindex
My current config for the site is
server {
listen 80;
server_name myname;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
location / {
root /var/www/html
fancyindex on;
fancyindex_exact_size off;
fancyindex_footer /fancy-index/footer.html;
fancyindex_header /fancy-index/header.html;
fancyindex_css_href /fancy-index/style.css;
fancyindex_time_format "%B %e, %Y";
}
}
I've also loaded the module in the nginx.conf on the first line of the file
load_module /usr/share/nginx/modules/ngx_http_fancyindex_module.so;
I also clarify that I am new to nginx, so I apologize if this is a common issue that I should be aware of.
Thanks in advance, any help would be much appreciated
I wasn't able to find a solution to use fancy index however, I've got a workaround by using the module ngx_http_addition_module on which fancy index is based.
This module is here : https://nginx.org/en/docs/http/ngx_http_addition_module.html
Basically, the configuration goes as follows :
location / {
root /var/www/html
addition_types text/html; # Replace this with watever mime type this server is responding
add_before_body /fancy-index/header.html; # Replace the fancyindex_header
add_after_body /fancy-index/footer.html; # Replace the fancyindex_footer
}
You don't have the possibility to link a stylesheet from these directives or changes the time format, but nothing prevent to load a stylesheet from the header and adding a script in it for the time.
I had the same problem. The issue is coming from the fact that you enable autoindex.
To fix the issue you need to comment the line that reference autoindex
I am quite new to NGINX and within this topic it is still very hard for me to find the right buzzwords to have more successful search results. That is why I try to descibe my problem here and maybe some of you can point me in the right direction. For my own personal project I want to set up a website which is composed from several micro services (which have all their own frontend).
My idea was to have one NGINX sever running serving as web server to deliver some kind of HTML which then includes the content of the micro services via server side includes (SSI).
Since the SSI can only include files and local folders as I understand I added some proxy_pass to my local server configuration:
http {
server {
listen 80;
ssi on;
root /usr/share/nginx/html;
location /led-todo {
proxy_pass http://led-todo-frontend:3000/;
}
}
}
So since I have the NGINX and my micro services in the same docker-compose running the URL: http://led-todo-frontend:3000 works.
The issue I am facing now is that when access my index.html page:
<html>
<head>
</head>
<body>
<!--# include virtual="test.html"-->
<!--# include virtual="/led-todo/"-->
</body>
</html>
The index.html content of my micro service is actually included into the above shown html site.
The issue arises when the script tags within my included html content are resolved:
<script src="/static/js/bundle.js">
The browser tries to load them from:
http://localhost:8080/static/js/bundle.js
Instead of:
http://localhost:8080/led-todo/static/js/bundle.js
Which then would again trigger the proxy pass to the correct micro service.
I feel like there should be some parameters to define the root or something so that /static/js/bundle.js is not loaded from localhost:8080 but from localhost:8080/led-todo in the following part of the NGINX configuration:
location /led-todo {
proxy_pass http://led-todo-frontend:3000/;
}
I tried several things I found in the internet here but somehow I am missing the words to describe this issue so that I can find results...
Anyone know how to solve this issue, or know at least some buzzwords I can search for?
This isn't a very elegant solution, but you can try to on-the-fly rewriting that tags content with the ngx_http_sub_module, something like this could work:
location /led-todo/ {
proxy_pass http://led-todo-frontend:3000/;
sub_filter_once off;
# uncomment to do substitution inside CCS or JS content too
# sub_filter_types text/css application/javascript;
sub_filter 'href="/' 'href="/led-todo/';
sub_filter "href='/" "href='/led-todo/";
sub_filter 'src="/' 'src="/led-todo/';
sub_filter "src='/" "src='/led-todo/";
}
I am having trouble figuring out how to serve static files for my Flask web app through Nginx and Gunicorn. All documentation I have seen online points to adding some path to static folder alias when a client makes a request for static files. However, I am not sure what the full path should be since the app is hosted on Heroku. All requests to static files are returning 404 errors. I also noticed that the XHR request to a JSON file stored in the directory path /static/json/<file>.json is not returning a JSON object on success.
Project Hierarchy:
project/
|_ config/
|_ gunicorn.conf.py
|_ nginx.conf.erb
|_ flask_app/
|_ __init__.py
|_ static/
|_ css/
|_ js/
|_ images/
|_ json/
|_ Procfile
|_ run.py
project/config/gunicorn.conf.py:
def when_ready(server):
open('/tmp/app-initialized', 'w').close()
bind = 'unix:///tmp/nginx.socket'
project/config/nginx.conf.erb:
daemon off;
#Heroku dynos have at least 4 cores.
worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;
events {
use epoll;
accept_mutex on;
worker_connections <%= ENV['NGINX_WORKER_CONNECTIONS'] || 1024 %>;
}
http {
server_tokens off;
log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
access_log <%= ENV['NGINX_ACCESS_LOG_PATH'] || 'logs/nginx/access.log' %> l2met;
error_log <%= ENV['NGINX_ERROR_LOG_PATH'] || 'logs/nginx/error.log' %>;
include mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
#Must read the body in 5 seconds.
client_body_timeout 5;
upstream app_server {
server unix:/tmp/nginx.socket fail_timeout=0;
}
server {
listen <%= ENV["PORT"] %>;
server_name _;
keepalive_timeout 5;
# Configure NGINX to deliver static content from the specified folder
location /static {
alias /static;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app_server;
}
}
}
project/Procfile
web: bin/start-nginx gunicorn -c config/gunicorn.conf.py 'run:create_app()'
worker: python worker.py
clock: python clock.py
example.js
export function getData() {
$.ajax({
type: 'GET',
url: '/static/json/data.json',
async: false,
success : function(data) {
currentPageIndex = 0;
numberOfPages = data.length; // Getting undefined error here on "data"
}
});
}
In your given configuration, there are (at least) two ways of hosting static content. It is not clear to me for which of the two alternatives below you decided - I have the impression you want to have somehow both?
I am sure you read https://flask.palletsprojects.com/en/1.1.x/tutorial/static/ which says
Flask automatically adds a static view that takes a path relative to the flaskr/static directory and serves it.
The URL would be the same as for your flask SPA with an additional static behind, see e.g. Link to Flask static files with url_for or https://flask.palletsprojects.com/en/1.1.x/quickstart/#url-building
The file location for the static content would be /static within your flask-app-directory.
Please also note How to serve static files in Flask which says
The preferred method is to use nginx or another web server to serve static files; they'll be able to do it more efficiently than Flask.
In this case, the Nginx docu on Serving Static Content is your friend:
The URL will be simply www.example.com/whateverHerokuPutsHere/static.
The file location can be anything you specify inside your nginx.conf, usually one would put absolute paths there.
Disclaimer: I never worked with heroku, so I am not sure whether there will be actually a whateverHerokuPutsHere. It could well be that it is simply example.com as you configure somewhere on Heroku's UI. For the file-location I found a blog Nginx as a static site server on Heroku.
use python code to render files
#app.route("/")
def main():
return render_template('main.html')
examples/flask/stat/templates/main.html
if you use static images
use relative path
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, user-scalable=yes">
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
<h1>Hello World</h1>
<img src="static/img/code_maven_128.png" />
</body>
</html>
The CSS itself is also very simple, its content is not relevant for our purposes.
examples/flask/stat/static/css/style.css
h1 {
color: blue;
}
How to run this
There are two simple ways to run this in developlent. For both you need to open your terminal (cmd window if you are on Windows), change to the directory where the application file (web.py in our case) can be found.
python web.py
A better way, that provides more control over how to run this is to use:
https://code-maven.com/flask-serve-static-files
enter code here
I found out that the issue was related to having an incorrect alias path. It was difficult to determine at first since Heroku has its root directory set up differently than I do on my local machine. The root directory for the Heroku application is /app so I changed the alias to this, based on my project hierarchy. This should work for anyone else facing similar issues.
location /static {
alias /app/flask_app/static;
}
I am trying to setup a Question2Answer website (yoalfaaz.com) on nginx with Ubuntu. Now, the homepage of the website does load but any other page doesn't load correctly. Mostly, when I click for any post on my website, it opens the homepage again and sometimes just breaks the layout.
Here's the sites-available file
server {
listen 80 ;
listen [::]:80 ;
root /var/www/yoalfaaz.com/html;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;
server_name yoalfaaz.com www.yoalfaaz.com;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.php$is_args$args;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
Now, previously only the homepage was opening and for every other page, I was getting 404 Not Found error. So I made some changes to try_files line and after that, the website pages are not opening in the correct way.
I have also checked for any kind of errors, but there are none and if I try nginx -t then it also shows successful. Please help me out, guys.
Apparently the problem is not nginx, but your application.
Looking at the HTML of your pages I see this:
<link href="./qa-plugin/q2a-embed-master/qa-embed.css" rel="stylesheet">
<link rel="stylesheet" href="./qa-plugin/q2a-tag-list-widget-master/tag-list.css?" TYPE="text/css">
<link rel="stylesheet" href="./qa-plugin/Welcome-Widget-master/welcome-widget.css?" TYPE="text/css">
The URLs of your CSS files are relative to the current path, so basically the location changes if the URL contains something that resembles a path or subdirectory.
Take for example this URL: http://yoalfaaz.com/4966/pardesi-ke-naam
Trying to load the CSS file ./qa-plugin/q2a-embed-master/qa-embed.css on that page will load http://yoalfaaz.com/4966/qa-plugin/q2a-embed-master/qa-embed.css which results in a 404 error.
You should change your code to output absolute URLs or root-relative URLs.
Example:
Absolute URL: http://yoalfaaz.com/qa-plugin/q2a-embed-master/qa-embed.css or //yoalfaaz.com/qa-plugin/q2a-embed-master/qa-embed.css (the last one is protocol-relative URL)
Root-relative URL: /qa-plugin/q2a-embed-master/qa-embed.css (always will start at the root of the domain)