CSS not loading for self-hosted Nginx with Jekyll /Hugo site - css

I am building a static website on my Olimex Lime2 board (Armbian OS) using Nginx as my webserver. My problem that no matter what static site builder or theme I use, when I go to view the public site, there is no CSS styling. Here is the public site: https://natehn.com
I have tried several themes on Hugo and Jekyll, with little or no modification to the default settings. This is why I think the issue is with Nginx.
I have explored this question and done plenty of Googling but was unable to determine a solution. I'm self-taught and don't know what I am looking for. Hopefully I missed something simple and this is an easy fix.
Here is my nginx.conf:
events {}
# Expires map
http {
map $sent_http_content_type $expires {
default off;
text/html 7d;
text/css max;
application/javascript max;
~image/ max;
}
server {
listen 80;
server_name natehn.com;
location / {
return 301 https://$server_name$request_uri;
}
}
server{
listen 443 ssl http2;
server_name natehn.com;
charset UTF-8; #improve page speed by sending the charset with the first response.
location / {
root /home/nathan/blog/public;
index index.html;
autoindex off
}
#Caching (save html pages for 7 days, rest as long as possible, no caching on frontpage)
expires $expires;
location #index {
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-cache, no-store';
etag off;
expires off;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#error_page 500 502 503 504 /50x.html;
#location = /50x.html {
# root /var/www/;
#}
#Compression
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# Logs
access_log /var/log/nginx/natehn.com.com_ssl.access.log;
error_log /var/log/nginx/natehn.com_ssl.error.log;
# SSL Settings:
ssl_certificate /etc/letsencrypt/live/natehn.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/natehn.com/privkey.pem;
# Improve HTTPS performance with session resumption
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 5m;
# Enable server-side protection against BEAST attacks
ssl_prefer_server_ciphers on;
ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;
# Disable SSLv3
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
# Lower the buffer size to increase TTFB
ssl_buffer_size 4k;
#CAUSED ERROR
# Diffie-Hellman parameter for DHE ciphersuites
# $ sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 4096
#ssl_dhparam /etc/ssl/certs/dhparam.pem;
# Enable HSTS (https://developer.mozilla.org/en-US/docs/Security/HTTP_Strict_Transport_Security)
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains";
# Enable OCSP stapling (http://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox)
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/natehn.com/fullchain.pem;
resolver 192.34.59.80 66.70.228.164 valid=300s;
resolver_timeout 5s;
}
}
And here is my sites-available/natehn.com, which is linked to sites-enabled:
server {
listen 80 default_server;
listen [::]:80 default_server;
# SSL configuration
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
root /home/nathan/blog/public;
# Add index.php to the list if you are using PHP
index.html;
server_name natehn.com www.natehn.com;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
}
I have explored everything I know. Any tips on where to look for potential solutions? Let me know if there is something else you need to look at.
Many thanks :) N

The css link has been blocked because of mixed content - the page is loaded over https:// but the href for the css is plain http://
Same will be true for your favicon etc.
As a general approach, to use the same protocol as the parent page, simply miss that off the href, for example:
<link rel="stylesheet" href="//natehn.com/css/style-white.css">
Edit: Better solution for site builders is to set the base URL to make sure constructed hrefs always use the correct protocol, https in your case:
For Hugo, see baseURL in https://gohugo.io/getting-started/configuration/
For Jekyll, see baseurl in https://jekyllrb.com/docs/configuration/options/
Wordpress and others have similar options.

Related

NGINX (Reverse Proxy - Bad Gateway

I searched a lot and tried a lot but on this point I dont get it... so here is my question:
I have a newly setup Proxmox and I wanna run a nginx reverse proxy and some VMs behind it. It is the first time with nginx and reverse proxy for me. I only used Apache before and never a reverse proxy.
So my reverse proxy has basicly three files: headers.conf, ssl.conf and my.domain.com.conf.
In headers.conf is the following:
#
# Add headers to serve security related headers
#
# HSTS (ngx_http_headers_module is required)
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload;" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Robots-Tag none always;
add_header X-Download-Options noopen always;
add_header X-Permitted-Cross-Domain-Policies none always;
add_header Referrer-Policy no-referrer always;
add_header X-Frame-Options "SAMEORIGIN" always;
# Remove X-Powered-By, which is an information leak
fastcgi_hide_header X-Powered-By;
#prox headers
proxy_set_header Host $host;
proxy_set_header X-Forwarded-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-Proto https;
Then there is the ssl.conf:
GNU nano 5.4 /etc/nginx/snippets/ssl.conf
#
# Configure SSL
#
# Diffie-Hellman parameter for DHE ciphersuites, recommended 4096 bits
ssl_dhparam /etc/nginx/dhparams/dhparams.pem;
# Not using TLSv1 will break:
# Android <= 4.4.40 IE <= 10 IE mobile <=10
# Removing TLSv1.1 breaks nothing else!
ssl_protocols TLSv1.2 TLSv1.3;
# SSL ciphers: RSA + ECDSA
# Two certificate types (ECDSA, RSA) are needed.
ssl_ciphers 'TLS-CHACHA20-POLY1305-SHA256:TLS-AES-256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-A>
# Use multiple curves.
ssl_ecdh_curve secp521r1:secp384r1;
# Server should determine the ciphers, not the client
ssl_prefer_server_ciphers on;
# SSL session handling
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
# SSL stapling has to be done seperately, becuase it will not work with self signed certs
# OCSP Stapling fetch OCSP records from URL in ssl_certificate and cache them
ssl_stapling on;
ssl_stapling_verify on;
# DNS resolver
resolver 192.168.xxx.xx;
and the my.domain.com.conf:
server {
listen 80;
listen [::]:80;
server_name my.domain.com;
location ~ \.* {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name my.domain.com;
# SSL configuration
# RSA certificates
ssl_certificate /etc/letsencrypt/my.domain.com/rsa/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/my.domain.com/rsa/key.pem;
# ECC certificates
ssl_certificate /etc/letsencrypt/my.domain.com/ecc/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/my.domain.com/ecc/key.pem;
# This should be ca.pem (certificate with the additional intermediate certificate)
# See here: https://certbot.eff.org/docs/using.html
# ECC
ssl_trusted_certificate /etc/letsencrypt/my.domain.com/ecc/ca.pem;
# Include SSL configuration
include /etc/nginx/snippets/ssl.conf;
# Include headers
include /etc/nginx/snippets/headers.conf;
# Set the access log location
access_log /var/log/nginx/my.domain.access.log;
location ~ \.* {
proxy_pass http://192.168.xxx.xxx:80;
proxy_read_timeout 90;
proxy_redirect http://192.168.xxx.xxx:80 https://my.domain.com;
}
}
That is the reverse proxy side.
The VM has nginx as well and the following file, my.domain.com.conf:
upstream php-handler {
server unix:/run/php/php7.4-fpm.sock;
}
server {
listen 80;
listen [::]:80;
server_name my.domain.com;
#root /var/www;
# location / {
# return 301 https://$host$request_uri;
# }
# Path to the root of your installation
root /var/www/nextcloud;
# Specify how to handle directories -- specifying `/index.php$request_uri`
# here as the fallback means that Nginx always exhibits the desired behaviour
# when a client requests a path that corresponds to a directory that exists
# on the server. In particular, if that directory contains an index.php file,
# that file is correctly served; if it doesn't, then the request is passed to
# the front-end controller. This consistent behaviour means that we don't need
# to specify custom rules for certain paths (e.g. images and other assets,
# `/updater`, `/ocm-provider`, `/ocs-provider`), and thus
# `try_files $uri $uri/ /index.php$request_uri`
# always provides the desired behaviour.
index index.php index.html /index.php$request_uri;
# set max upload size and increase upload timeout:
client_max_body_size 512M;
client_body_timeout 300s;
fastcgi_buffers 64 4K;
# Enable gzip but do not remove ETag headers
gzip on;
gzip_vary on;
gzip_comp_level 4;
gzip_min_length 256;
gzip_proxied expired no-cache no-store private no_last_modified no_etag auth;
gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;
# Rule borrowed from `.htaccess` to handle Microsoft DAV clients
location = / {
if ( $http_user_agent ~ ^DavClnt ) {
return 302 /remote.php/webdav/$is_args$args;
}
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# Make a regex exception for `/.well-known` so that clients can still
# access it despite the existence of the regex rule
# `location ~ /(\.|autotest|...)` which would otherwise handle requests
# for `/.well-known`.
location ^~ /.well-known {
# The rules in this block are an adaptation of the rules
# in `.htaccess` that concern `/.well-known`.
location = /.well-known/carddav { return 301 /remote.php/dav/; }
location = /.well-known/caldav { return 301 /remote.php/dav/; }
#location /.well-known/acme-challenge { try_files $uri $uri/ =404; }
#location /.well-known/pki-validation { try_files $uri $uri/ =404; }
# Let Nextcloud's API for `/.well-known` URIs handle all other
# requests by passing them to the front-end controller.
return 301 /index.php$request_uri;
}
# Rules borrowed from `.htaccess` to hide certain paths from clients
location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)(?:$|/) { return 404; }
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) { return 404; }
# Ensure this block, which passes PHP files to the PHP process, is above the blocks
# which handle static assets (as seen below). If this block is not declared first,
# then Nginx will encounter an infinite rewriting loop when it prepends `/index.php`
# to the URI, resulting in a HTTP 500 error response.
location ~ \.php(?:$|/) {
# Required for legacy support
rewrite ^/(?!index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+|.+\/richdocumentscode\/proxy) /index.php$request_uri;
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
set $path_info $fastcgi_path_info;
try_files $fastcgi_script_name =404;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $path_info;
fastcgi_param HTTPS on;
fastcgi_param modHeadersAvailable true; # Avoid sending the security headers twice
fastcgi_param front_controller_active true; # Enable pretty urls
fastcgi_pass php-handler;
fastcgi_intercept_errors on;
fastcgi_request_buffering off;
fastcgi_read_timeout 600;
fastcgi_send_timeout 600;
fastcgi_connect_timeout 600;
fastcgi_param PHP_VALUE "upload_max_filesize = 10G
post_max_size = 10G
max_execution_time = 3600
output_buffering = off";
}
location ~ \.(?:css|js|svg|gif|png|jpg|ico|wasm|tflite)$ {
try_files $uri /index.php$request_uri;
expires 6M; # Cache-Control policy borrowed from `.htaccess`
access_log off; # Optional: Don't log access to assets
location ~ \.wasm$ {
default_type application/wasm;
}
}
location ~ \.woff2?$ {
try_files $uri /index.php$request_uri;
expires 7d; # Cache-Control policy borrowed from `.htaccess`
access_log off; # Optional: Don't log access to assets
}
# Rule borrowed from `.htaccess`
location /remote {
return 301 /remote.php$request_uri;
}
}
I did all that from reading different tutorials and the manuals itself. But I totally don't get my mistake.... is there anything obvies you can see? I feel very happy for any hint you guys have for me!
Thank you a lot and good christmas time :)
This is the output:
root#HL-Reverse-Proxy:/var/www# telnet 192.168.178.100 80
Trying 192.168.178.100...
Connected to 192.168.178.100.
Escape character is '^]'.
GET /
<html>
<head><title>502 Bad Gateway</title></head>
<body>
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.21.4</center>
</body>
</html>
Connection closed by foreign host.
So connection is possible.

NGINX - Directive to Allow iPhone's IP address for accessing wordpress login page (mysite.com/wp-login.php), and Deny all other IP addresses

MY ENVIRONMENT:
I am running a LEMP server which is working and running wordpress quite properly. As of now, I have my wordpress web login (www.mysite/wp-login.php) blacklisted by all IP addresses EXCEPT any IP on my LAN with the following directive:
server {
# Allow LAN only on wp-login page (www.mysite.com/wp-login.php)
location ~ /wp-login.php {
allow 192.168.1.0/24;
deny all;
}
This directive sucessfully blocks all internet traffic to "mywebsite.com/wp-login.php", which is the wordpress admin login page.
In other words, with this directive set, I can access the wordpress login page anywhere on my internal LAN, but the directive denys any outside internet traffic from seeing the "mywebsite.com/wp-login.php" page. GREAT!
WHAT I WANT TO DO,
is to whitelist the IP address of my phone, so that I can access the wordpress login page from my phone's IP address, while still blocking any other outside internet traffic. To do so, I go to www.whatsmyip.org on my phone, copy the ip address that it gives me, then modify the previous directive to look like the following:
server {
# Allow LAN and CellPhone access to to wp-login page (www.mysite.com/wp-login.php)
location ~ /wp-login.php {
allow 77.232.28.46; # my phones ip address as shown on whatsmyip.org
allow 192.168.1.0/24;
deny all;
}
HOWEVER,
after reloading nginx, I still cannot access the wp-login (wordpress login) page from my phone.
MY QUESTION IS:
Using NGINX, How can I properly whitelist my phones IP address, while blacklisting everything else access to the wordpress login page locate at www.mysite.com/wp-login.php ?
FOR REFERENCE:
Below is my NGINX.CONF file:
# This is the /etc/nginx/nginx.conf file for Danrancan's LEMP server
#
user www-data;
worker_processes 4;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
load_module /usr/share/nginx/modules/ngx_http_modsecurity_module.so;
events {
worker_connections 1024;
# multi_accept on;
}
http {
##
# Mod Security
##
modsecurity on;
#modsecurity off;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
##
# Basic Settings
##
client_max_body_size 512M;
fastcgi_read_timeout 300;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
types_hash_max_size 4096;
server_tokens off;
server_names_hash_bucket_size 64;
# server_name_in_redirect off;
# Create a custom Nginx log format called netdata that includes information about request_time, and upstream_response_time, measured in seconds with millisecond resolution.
log_format netdata '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'$request_length $request_time $upstream_response_time '
'"$http_referer" "$http_user_agent"';
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# SSL Settings
##
ssl_session_cache shared:SSL:10m; #SSL session cache
ssl_session_timeout 1h;
ssl_prefer_server_ciphers on;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types
application/atom+xml
application/javascript
application/json
application/rss+xml
application/vnd.ms-fontobject
application/x-font-ttf
application/x-web-app-manifest+json
application/xhtml+xml
application/xml
font/opentype
image/svg+xml
image/x-icon
text/css
text/plain
text/x-component
text/javascript
text/xml;
# Extra Http Header response to determine whether a request is being served from the cache
#add_header Fastcgi-Cache $upstream_cache_status;
##
# Virtual Host Configs
##
upstream local_php {
server unix:/run/php/php7.4-fpm.sock;
}
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
include /etc/nginx/perfect-forward-secrecy.conf;
##
# Harden nginx against DDOS. #noted from www.pestmeester.nl
##
client_header_timeout 10;
# For good security, set client_body_timeout to 10. For uploading large files, set to higher.
client_body_timeout 10;
keepalive_timeout 10;
send_timeout 10;
}
and my VIRTUAL HOST CONFIG:
# Danrancan's Virtual host config for /etc/nginx/sites-available/mysite.com.conf
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name mysite.com www.mysite.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
###
# SSL (From Mozilla Config Generator: Modern Configuration)
###
# Add Strict Transport Security Response Header with "always Paramater", to help prevent MITM attacks.
# HSTS (ngx_http_headers_module is required) (63072000 seconds)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
## Prevent click jacking by adding an X-Frame header
# Add X-Frame-Options header to nginx with the following line:
add_header x-frame-options "SAMEORIGIN" always;
# Add a content security policy header
add_header Content-Security-Policy "frame-ancestors 'self';";
# Secure MIME Types with X-Content-Type-Options. Below line adds the X-Fram-Options header in Nginx.
add_header X-Content-Type-Options nosniff;
# Enable X-XSS-Protection header in Nginx
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin";
add_header Permissions-Policy "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=(),magnetometer=(),gyroscope=(),fullscreen=(self),payment=()";
# Path to signerd certificate + Intermediate certificates
ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; # Managed by admin
ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; # Managed by admin
# Perfect Forward Secrecy Diffie-Hellman 4096 parameters
ssl_dhparam /etc/ssl/private/dhparams4096.pem; # Managed by admin
# Include "perfect-forward-secrecy.conf" file in this virtual host. NOTE: No need to do this, as its already included in the nginx.conf file, so you should comment this out.
#include /etc/nginx/perfect-forward-secrecy.conf; # Managed by admin
# Modern SSL configuration with OCSP stapling turned on
#ssl_protocols TLSv1.3; # commented out because its already in the nginx.conf file
ssl_prefer_server_ciphers on;
ssl_session_timeout 1d;
ssl_session_cache shared:MozSSL:10m; # about 40000 sessions
ssl_session_tickets off;
# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4;
# Verify chain of trust of OCSP response using Root CA and Intermediate certs
ssl_trusted_certificate /etc/letsencrypt/live/mysite.com/chain.pem; # Managed by admin
server_name mysite.com www.mysite.com;
root /var/www/mysite.com;
# Error & Access Logs
#error_log /var/www/mysite.com.logs/error.log error;
#access_log /var/www/mysite.com.logs/access.log;
access_log /var/log/nginx/mysite.com.access.log netdata;
error_log /var/log/nginx/mysite.com.error.log warn;
# This should be in your http block and if it is, it's not needed here.
index index.php index.html index.htm;
# Only allow access of /admin via internal IP
location ^~ /admin {
allow 192.168.1.0/24;
deny all;
error_page 403 =444;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
}
# Allow local only to wp-login page
location ~ /wp-login.php {
allow 192.168.1.0/24;
deny all;
error_page 403 =444;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
}
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ /.well-known {
allow all;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# Cache Static Files For As Long As Possible
location ~*\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
access_log off;
log_not_found off;
expires max;
}
# Security Settings For Better Privacy Deny Hidden Files
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# Disallow PHP In Upload Folder
location /wp-content/uploads/ {
location ~ \.php$ {
deny all;
}
}
# Pass PHP scripts to FastCGI server
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php-fpm (or other unix sockets):
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# Below was Added from recommended by pestmeester.nl
fastcgi_intercept_errors on;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}
What you are doing should work.
Since it is not, it seems that for some reason nginx doesn't see your phone IP as a match to what you have configured.
It sounds like your WP box is running on a private network (because of the 192.168.1.0/ IP addresses you mentioned).
When you connect to the WP box from the internet, is it going through a router with port forwarding/NAT?
First thing I would do is just tail your nginx access log (access_log /var/log/nginx/access.log;) when trying to access with your iphone and see what is reported.
If the request is coming through a proxy/reverse-proxy you may need to make sure the proxy is adding X-Forwarded-For to pass along the remote (iphone) ip address. The request to nginx/wp would be coming from the proxy IP and there would be a header X-Forwarded-For added to the request containing the original remote address.
When nginx is used this way you need to use nginx's realip module...something like:
real_ip_header X-Forwarded-For;
set_real_ip_from 192.168.1.1; # proxy ip
http://nginx.org/en/docs/http/ngx_http_realip_module.html

How can I redirect non-www to www in https NGINX

I have a question related with Nginx redirects
Bellow you can see configurations.
My goal is to redirect from https://example.com to https://www.example.com
I looked through almost all in stackoverflow and I didn't find any help. Please help me with this issue. I will provide all necessary information about my Nginx Web Server.
I hope you will help me, with this difficult question.
My file nginx.conf looks like there:
user www-data;
worker_processes 4;
pid /run/nginx.pid;
events {
worker_connections 768;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_names_hash_bucket_size 64;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_static on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 9;
# gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xm$
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
My file /etc/nginx/sites-enabled/example:
server {
listen 80;
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com;
ssl_stapling on;
ssl on;
ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; # managed by Certbot
root /var/www/example/public;
index ../views/index.html;
location /img/ {
proxy_pass http://127.0.0.1:3010;
proxy_cache off;
proxy_cache_key "$proxy_host$uri$is_args$args";
}
location / {
proxy_pass http://127.0.0.1:3010;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|css|js|html)$ {
root /var/www/example/public;
expires 1y;
access_log off;
add_header Cache-Control "public";
}
}
Just create a server for non-www requests, for example:
# redirect http to https
server {
listen 80;
server_name www.example.com example.com;
return 301 https://www.example.com$request_uri;
}
# redirect http://example.com to https://www.example.com
server {
listen 443 ssl;
server_name example.com;
# ssl ...
return 301 https://www.example.com$request_uri;
}
# https://www.example.com
server {
listen 443 ssl;
server_name www.example.com;
# ssl ...
}
The DNS records for example.com and www.example.com should be pointing to your Nginx server
Quick instruction for redirect and also for ssl
Don't write all conf all your sites in one file nginx.conf. Separate these. You have two folders for it /etc/nginx/sites-available/ and /etc/nginx/sites-enabled/
Add file for your site for example /etc/nginx/sites-available/example
Make link ln -s /etc/nginx/sites-enabled/example
To this conf file paste text below:
server {
listen 80;
server_name example.com www.cova.company;
return 301 https://www.example.company$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com;
ssl_stapling on;
ssl on;
ssl_certificate /etc/letsencrypt/live/www.site.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.site.com/privkey.pem;
# your location there a
}
In you nginx.conf ypu already have row include /etc/nginx/sites-enabled/*; it means automatically take all of their sites configs from folder sites-enabled
After it check syntax with command nginx -t and reload your nginx with command systemctl reload nginx
And after all off this who call your site via http://example.com or https://example.com will be redirected to https://www.example.com

Nginx ERR_CONNECTION_RESET only one domain name

Problem
Other sites work with exactly the same configuration, but one site is different and does not work. Browser outputs ERR_CONNECTION_RESET. Nginx logs 6819 # 0: signal process started.
If you change server _name to another domain then everything works.
Help someone who came across. Thank you.
My config nginx:
server {
server_name example.com *.example.com;
listen 80;
return 301 https://$host$request_uri;
}
server {
server_name example.com *.example.com;
listen 443 ssl http2;
# resolver 8.8.8.8;
root /usr/share/nginx/sites/example.com/html;
keepalive_timeout 65;
gzip on;
gzip_disable "msie6";
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
#autoindex on;
index index.php index.html index.htm;
ssl on;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
location ~ /.well-known {
allow all;
}
error_page 404 /404.html;
# proxy the PHP scripts to Apache listening on 127.0.0.1:8080
#
location ~ \.php$ {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://127.0.0.1:8080;
}}
I solved this problem... Proxy server didn't work. Face palm.

Open site both on site.name and www.site.name

I tried to achieve this as described in the manual (server_name .site.name), but it not seem to work (404 Not found). Can I do this without redirecting?
Here is the config.
server {
listen 80;
listen 443 ssl;
server_name .site.name;
ssl_certificate certs/mshop-production.crt;
ssl_certificate_key certs/mshop-production.key;
passenger_set_cgi_param HTTP_X_FORWARDED_PROTO $scheme;
error_log /var/log/nginx/mshop-production.error.log error;
access_log /var/log/nginx/mshop-production.access.log;
root /home/deployer/apps/production/mshop/current/public;
passenger_enabled on;
rails_env production;
gzip on;
gzip_types application/x-javascript application/javascript text/javascript text/css;
client_max_body_size 50m;
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 1M;
}
}
why not modify your A query record in your domain-name server?
I think it is more simple for you .
server_name server.name www.server.name;
would do. You can also use wildcards
server_name server.name *.server.name;

Resources