Nginx redirects to first Subdomain when accessing second - nextcloud

So here's my situation: I have a Nextcloud and OpenHAB set up on my server and want to access both from outside my local network. I use Nginx as my reverse proxy to access my nextcloud on cloud.foo.bar and my openHAB on home.foo.bar. This works for my cloud, however if I access home.foo.bar, I either get redirected to cloud.foo.bar (on my Windows 10 machine) or just access my nextcloud under the home.foo.bar domain. Here's my nginx config (sites-available/default).
server {
listen 80;
server_name home.foo.bar;
location / {
proxy_pass http://localhost:8080/;
proxy_set_header Host $http_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 $scheme;
}
}
upstream php-handler {
#server 127.0.0.1:9000;
server unix:/var/run/php/php7.2-fpm.sock;
}
server {
if ($host = cloud.foo.bar) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name cloud.foo.bar;
# enforce https
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name cloud.foo.bar;
ssl_certificate /etc/letsencrypt/live/cloud.foo.bar/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/cloud.foo.bar/privkey.pem; # managed by Certbot
# Add headers to serve security related headers
# Before enabling Strict-Transport-Security headers please read into this
# topic first.
# add_header Strict-Transport-Security "max-age=15768000;
# includeSubDomains; preload;";
#
# WARNING: Only add the preload option once you read about
# the consequences in https://hstspreload.org/. This option
# will add the domain to a hardcoded list that is shipped
# in all major browsers and getting removed from this list
# could take several months.
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header X-Robots-Tag none;
add_header X-Download-Options noopen;
add_header X-Permitted-Cross-Domain-Policies none;
# Path to the root of your installation
root /var/www/nextcloud/;
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# The following 2 rules are only needed for the user_webfinger app.
# Uncomment it if you're planning to use this app.
#rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
#rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json
# last;
location = /.well-known/carddav {
return 301 $scheme://$host/remote.php/dav;
}
location = /.well-known/caldav {
return 301 $scheme://$host/remote.php/dav;
}
# set max upload size
client_max_body_size 512M;
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;
# Uncomment if your server is build with the ngx_pagespeed module
# This module is currently not supported.
#pagespeed off;
location / {
rewrite ^ /index.php$request_uri;
}
location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ {
deny all;
}
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
deny all;
}
location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+)\.php(?:$|/) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param HTTPS on;
#Avoid sending the security headers twice
fastcgi_param modHeadersAvailable true;
fastcgi_param front_controller_active true;
fastcgi_pass php-handler;
fastcgi_intercept_errors on;
fastcgi_request_buffering off;
}
location ~ ^/(?:updater|ocs-provider)(?:$|/) {
try_files $uri/ =404;
index index.php;
}
# Adding the cache control header for js and css files
# Make sure it is BELOW the PHP block
location ~ \.(?:css|js|woff|svg|gif)$ {
try_files $uri /index.php$request_uri;
add_header Cache-Control "public, max-age=15778463";
# Add headers to serve security related headers (It is intended to
# have those duplicated to the ones above)
# Before enabling Strict-Transport-Security headers please read into
# this topic first.
# add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
#
# WARNING: Only add the preload option once you read about
# the consequences in https://hstspreload.org/. This option
# will add the domain to a hardcoded list that is shipped
# in all major browsers and getting removed from this list
# could take several months.
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header X-Robots-Tag none;
add_header X-Download-Options noopen;
add_header X-Permitted-Cross-Domain-Policies none;
# Optional: Don't log access to assets
access_log off;
}
location ~ \.(?:png|html|ttf|ico|jpg|jpeg)$ {
try_files $uri /index.php$request_uri;
# Optional: Don't log access to other assets
access_log off;
}
}
I only have an A record for the ipv4 of the server for #foo.bar, I tried using two records for cloud.foo.bar and home.foo.bar pointing towards the same ipv4, which didn't change anything.

I seem to answer a lot of my question just after posting them myself... I had to add a redirect for https requests, as my configurations forwareded all requests on port 80 to port 443 which only has a listener for cloud.foo.bar.

Related

Letsencrypt / nginx : SSL configuration went wrong

I recently acquired a domain name that I want to point to my home server. It worked very well before I tried to implement SSL. Since then I get this error when I try to access https://cloud.mydomain.com/:
SSL_ERROR_RX_RECORD_TOO_LONG
I don't know how to debug on this at all.
With my host here is my config:
mydomain.com. A [my external IP]
cloud.mydomain.com. CNAME mydomain.com.
On my server I have this:
user www-data;
worker_processes auto;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
http {
server_names_hash_bucket_size 64;
upstream php-handler {
server unix:/run/php/php7.3-fpm.sock;
}
set_real_ip_from 127.0.0.1;
set_real_ip_from 192.168.1.0/24;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
include /etc/nginx/mime.types;
# include /etc/nginx/proxy.conf;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_connect_timeout 3600;
proxy_send_timeout 3600;
proxy_read_timeout 3600;
proxy_redirect off;
# include /etc/nginx/ssl.conf;
ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# include /etc/nginx/header.conf;
add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
add_header X-Robots-Tag none;
add_header X-Download-Options noopen;
add_header X-Permitted-Cross-Domain-Policies none;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer" always;
add_header X-Frame-Options "SAMEORIGIN";
# include /etc/nginx/optimization.conf;
fastcgi_hide_header X-Powered-By;
fastcgi_read_timeout 3600;
fastcgi_send_timeout 3600;
fastcgi_connect_timeout 3600;
fastcgi_buffers 64 64K;
fastcgi_buffer_size 256k;
fastcgi_busy_buffers_size 3840K;
fastcgi_cache_key $http_cookie$request_method$host$request_uri;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
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;
gzip_disable "MSIE [1-6]\.";
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log warn;
sendfile on;
send_timeout 3600;
tcp_nopush on;
tcp_nodelay on;
open_file_cache max=500 inactive=10m;
open_file_cache_errors on;
keepalive_timeout 65;
reset_timedout_connection on;
server_tokens off;
resolver 192.168.1.1 valid=30s;
resolver_timeout 5s;
# include /etc/nginx/conf.d/*.conf;
# etc/nginx/conf.d/nextcloud.conf;
server {
server_name cloud.mydomain.com;
listen 80 default_server;
listen [::]:80 default_server;
location / {
return 301 https://$host$request_uri;
}
}
server {
server_name cloud.mydomain.com;
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
root /var/www/nextcloud/;
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location = /.well-known/carddav {
return 301 $scheme://$host/remote.php/dav;
}
location = /.well-known/caldav {
return 301 $scheme://$host/remote.php/dav;
}
#SOCIAL app enabled? Please uncomment the following row
#rewrite ^/.well-known/webfinger /public.php?service=webfinger last;
#WEBFINGER app enabled? Please uncomment the following two rows.
#rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
#rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json last;
client_max_body_size 10240M;
location / {
rewrite ^ /index.php;
}
location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ {
deny all;
}
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
deny all;
}
location ^~ /apps/rainloop/app/data {
deny all;
}
location ~ \.(?:flv|mp4|mov|m4a)$ {
mp4;
mp4_buffer_size 100M;
mp4_max_buffer_size 1024M;
fastcgi_split_path_info ^(.+?.php)(\/.*|)$;
set $path_info $fastcgi_path_info;
try_files $fastcgi_script_name =404;
include fastcgi_params;
include php_optimization.conf;
}
location ~ ^\/(?:index|remote|public|cron|core\/ajax\/update|status|ocs\/v[12]|updater\/.+|oc[ms]-provider\/.+).php(?:$|\/) {
fastcgi_split_path_info ^(.+?.php)(\/.*|)$;
set $path_info $fastcgi_path_info;
try_files $fastcgi_script_name =404;
include fastcgi_params;
include php_optimization.conf;
}
location ~ ^\/(?:updater|oc[ms]-provider)(?:$|\/) {
try_files $uri/ =404;
index index.php;
}
location ~ .(?:css|js|woff2?|svg|gif|map|png|html|ttf|ico|jpg|jpeg)$ {
try_files $uri /index.php$request_uri;
access_log off;
expires 360d;
}
}
}
Here is the command I ran to generate the certificates:
sudo certbot --nginx -d mydomain.com -d cloud.mydomain.com
Note that when I access it from the local network with the address of the machine I have the certificate and the nextcloud is displayed.
My router is configured to transfer calls 80 and 443 on my machine and I can see the logs on /var/log/nginx/access.log
When I run the command:
openssl s_client -connect cloud.mydomain.com:443 -servername mydomain.com
I have the following result:
CONNECTED(00000003)
140509444985920:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../ssl/record/ssl3_record.c:332:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 5 bytes and written 317 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
Would you know how to debug this please?

Nginx is not proxying to the node backend

I have react application running on Nginx and backend application on Nodejs(running on another port 8080) with routes of patterns "/org-metadata/**, /proxy-api/**, /node-api/**".
I am trying to proxy the nginx to nodejs running on 8080, but it does not reach the backend. and the nginx gives the 503 Service Unavailable response and some times response 200 with You need to enable JavaScript to run this app.
Can some one pls point where am I missing anything?
Below is my nginx.conf file :
worker_processes auto;
events {
worker_connections 8000;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server {
# listen on port 80
listen 80;
# where the root here
root /var/www;
# what file to server as index
index index.html index.htm;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to redirecting to index.html
try_files $uri $uri/ /index.html;
}
# Javascript and CSS files
location ~* \.(?:css|js)$ {
try_files $uri =404;
expires 1y;
access_log off;
add_header Cache-Control "public";
}
location ~ (proxy-api|org-metadata|node-api) {
try_files $uri #nodejs;
}
location #nodejs {
proxy_pass http://nodejs:8080;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
}
}
}

Owncloud/Nginx on Arch - Site can't be reached

I have installed the arch system on my raspberry pi 3. After the instalation i have followed this guide on how to configure the owncloud. For the SSl Certificate i have followed the instructions from the arch owncloud documentation.
etc/nginx/nginx.conf
http{
include /etc/nginx/conf.d/*.conf;
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#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 /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
# }
}
/etc/nginx/conf.d/owncloud.conf
#upstream php-handler {
#server 127.0.0.1:9000;
# server unix:/run/php-fpm/php-fpm.sock;
#}
server {
listen 80;
server_name mycloud.go.com;
# enforce https
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name mycloud.go.com;
ssl_certificate ssl/server.crt;
ssl_certificate_key ssl/server.key;
# Add headers to serve security related headers
add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Robots-Tag none;
# Path to the root of your installation
root /usr/share/webapps/owncloud;
# set max upload size
client_max_body_size 10G;
fastcgi_buffers 64 4K;
# Disable gzip to avoid the removal of the ETag header
gzip off;
# Uncomment if your server is build with the ngx_pagespeed module
# This module is currently not supported.
#pagespeed off;
index index.php;
error_page 403 /core/templates/403.php;
error_page 404 /core/templates/404.php;
rewrite ^/.well-known/carddav /remote.php/carddav/ permanent;
rewrite ^/.well-known/caldav /remote.php/caldav/ permanent;
# The following 2 rules are only needed for the user_webfinger app.
# Uncomment it if you're planning to use this app.
#rewrite ^/.well-known/host-meta /public.php?service=host-meta last;
#rewrite ^/.well-known/host-meta.json /public.php?service=host-meta-json last;
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location ~ ^/(build|tests|config|lib|3rdparty|templates|data)/ {
deny all;
}
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
deny all;
}
location / {
rewrite ^/remote/(.*) /remote.php last;
rewrite ^(/core/doc/[^\/]+/)$ $1/index.html;
try_files $uri $uri/ =404;
}
location ~ \.php(?:$|/) {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param HTTPS on;
fastcgi_param modHeadersAvailable true; #Avoid sending the security headers twice
fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
fastcgi_intercept_errors on;
}
# Adding the cache control header for js and css files
# Make sure it is BELOW the location ~ \.php(?:$|/) { block
location ~* \.(?:css|js)$ {
add_header Cache-Control "public, max-age=7200";
# Add headers to serve security related headers
add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Robots-Tag none;
# Optional: Don't log access to assets
access_log off;
}
# Optional: Don't log access to other assets
location ~* \.(?:jpg|jpeg|gif|bmp|ico|png|swf)$ {
access_log off;
}
}
And when I access the server name from my browser it gives me this:
This site can’t be reached
mycloud.go.com refused to connect.
My ssl certificates are located in:
/etc/nginx/ssl
Also after I check the syntax of owncloud.conf it gives me:
2016/08/19 14:03:02 [emerg] 1513#1513: "server" directive is not allowed here in /etc/nginx/conf.d/owncloud.conf:6
nginx: configuration file /etc/nginx/conf.d/owncloud.conf test failed
I have found what the problem was. I was setting the wrong port in my router. I was setting the 80 external port and it needed to be 443. Also here is my owncloud.conf which is working
server {
listen 80;
server_name localhost;
return 301 https://$server_name$request_uri;
}
server {
listen 443;
ssl on;
server_name localhost;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
# Add headers to serve security related headers
add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Robots-Tag none;
# Path to the root of your installation
root /usr/share/webapps/owncloud;
# set max upload size
client_max_body_size 10G;
fastcgi_buffers 64 4K;
# Disable gzip to avoid the removal of the ETag header
gzip off;
# Uncomment if your server is build with the ngx_pagespeed module
# This module is currently not supported.
#pagespeed off;
index index.php;
error_page 403 /core/templates/403.php;
error_page 404 /core/templates/404.php;
rewrite ^/.well-known/carddav /remote.php/carddav/ permanent;
rewrite ^/.well-known/caldav /remote.php/caldav/ permanent;
location ~ /.well-known {
allow all;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location ~ ^/(build|tests|config|lib|3rdparty|templates|data)/ {
deny all;
}
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
deny all;
}
location / {
rewrite ^/remote/(.*) /remote.php last;
rewrite ^(/core/doc/[^\/]+/)$ $1/index.html;
try_files $uri $uri/ =404;
}
location ~ \.php(?:$|/) {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param HTTPS on;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param modHeadersAvailable true;
fastcgi_intercept_errors on;
include fastcgi_params;
}
# Adding the cache control header for js and css files
# Make sure it is BELOW the location ~ \.php(?:$|/) { block
location ~* \.(?:css|js)$ {
add_header Cache-Control "public, max-age=7200";
# Add headers to serve security related headers
add_header Strict-Transport-Security "max-age=15768000; includeSubDomains; preload;";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Robots-Tag none;
# Optional: Don't log access to assets
access_log off;
}
# Optional: Don't log access to other assets
location ~* \.(?:jpg|jpeg|gif|bmp|ico|png|swf)$ {
access_log off;
}
}

HTTPS www to non-www on NGINX

I'm having issues redirecting from www to non-www only for https/ssl. Any ideas why this might be happening? It works fine for non-secure URL's. Here's my config:
html {
# Compression
# Enable Gzip compressed.
gzip on;
# Enable compression both for HTTP/1.0 and HTTP/1.1.
gzip_http_version 1.1;
# Compression level (1-9).
# 5 is a perfect compromise between size and cpu usage, offering about
# 75% reduction for most ascii files (almost identical to level 9).
gzip_comp_level 5;
# Don't compress anything that's already small and unlikely to shrink much
# if at all (the default is 20 bytes, which is bad as that usually leads to
# larger files after gzipping).
gzip_min_length 128;
# Compress data even for clients that are connecting to us via proxies,
# identified by the "Via" header (required for CloudFront).
gzip_proxied any;
# Tell proxies to cache both the gzipped and regular version of a resource
# whenever the client's Accept-Encoding capabilities header varies;
# Avoids the issue where a non-gzip capable client (which is extremely rare
# today) would display gibberish if their proxy gave them the gzipped version.
gzip_vary on;
# Compress all output labeled with one of the following MIME-types.
gzip_types application/atom+xml application/x-javascript 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;
}
server {
listen 80;
server_name www.example.com example.com;
return 301 https://example.com$request_uri;
}
server {
listen *:443 ssl;
server_name www.example.com;
return https://example.com$request_uri 301;
}
server {
listen 443 ssl;
server_name example.com;
root /home/forge/default/public;
index index.html index.htm index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/default-error.log error;
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_param DB_PASSWORD "password";
fastcgi_param DB_USERNAME "user";
fastcgi_param DB_NAME "db";
fastcgi_param DB_HOST "localhost";
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
# Expire rules for static content
# cache.appcache, your document html and data
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
expires -1;
# access_log logs/static.log; # I don't usually include a static log
}
# Feed
location ~* \.(?:rss|atom)$ {
expires 1h;
add_header Cache-Control "public";
}
# Media: images, icons, video, audio, HTC
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
expires 1M;
access_log off;
add_header Cache-Control "public";
}
# CSS and Javascript
location ~* \.(?:css|js)$ {
expires 1y;
access_log off;
add_header Cache-Control "public";
}
}
OK, so I figured this out a while ago but forgot to post the answer, so here it is.
server {
listen 80;
server_name www.example.com example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
root /home/forge/default/public;
if ($host = 'www.example.com') {
rewrite ^/(.*)$ https://example.com/$1 permanent;
}
}
How robust this is I'm not entirely sure but it works.
Essentially, you listen on port 80 for www and non-www and return a 301 redirect to the secure non-www URL. You then check in your SSL server block listening on port 443 if the host that has been requested matches the www version of the secure URL and if it does you permanently rewrite it to the secure non-www version.
nginx takes SSL-certificate from 'default_server' or from first described for the particular IP+port pair.
So, you should
swap SSL-enabled server blocks
or just add default_server parameter to listen directive in your second block.

Installed Nginx now MP3 files aren't being cached by the browser

I've been using a vanilla apache install until recently with no major problems.
Today I installed Nginx Admin (the cpanel nginx plugin) which acts as a reverse proxy for Apache to deliver static files.
This all works very well and there is a noticable performance boost which I am pleased with.
However my site hosts a large amount of MP3 files which prior to using Nginx would all get cached by the browser meaning that a user only had to download them once and subsequent listens were instananeous.
Now, with Nginx Admin installed the browser requests the file from the server every time.
I have tried adding the following to my nginx config file:-
location ~* \.(mp3)$ {
expires max;
}
But even this had no effect. What might be causing this and what else can I try to rectify this issue?
Strangely under apache my header looks like this:-
Server Apache
Connection Keep-Alive
Keep-Alive timeout=5, max=98
Vary Accept-Encoding,User-Agent
This returns a 304 Not Modified response after being cached
and with nginx admin installed the headers are as follows:-
Server nginx admin
Date Thu, 24 Nov 2011 12:46:27 GMT
Content-Type audio/mpeg
Content-Length 5263187
Last-Modified Mon, 26 Sep 2011 18:29:39 GMT
Connection keep-alive
Expires Thu, 01 Dec 2011 12:46:27 GMT
Cache-Control max-age=604800
X-Cache HIT from Backend
Accept-Ranges bytes
Which no matter what always returns a 200 OK.
My nginx config file is as follows:-
user nobody;
# no need for more workers in the proxy mode
worker_processes 4;
error_log /var/log/nginx/error.log info;
worker_rlimit_nofile 20480;
events {
worker_connections 5120; # increase for busier servers
use epoll; # you should use epoll here for Linux kernels 2.6.x
}
http {
server_name_in_redirect off;
server_names_hash_max_size 10240;
server_names_hash_bucket_size 1024;
include mime.types;
default_type application/octet-stream;
server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 5;
gzip on;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
gzip_proxied any;
gzip_http_version 1.1;
gzip_min_length 1000;
gzip_comp_level 6;
gzip_buffers 16 8k;
# You can remove image/png image/x-icon image/gif image/jpeg if you have slow CPU
gzip_types text/plain text/xml text/css application/x-javascript application/xml image/png image/x-icon image/gif image/jpeg application/xml+rss text/javascript application/atom+xml;
ignore_invalid_headers on;
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
reset_timedout_connection on;
connection_pool_size 256;
client_header_buffer_size 256k;
large_client_header_buffers 4 256k;
client_max_body_size 200M;
client_body_buffer_size 128k;
request_pool_size 32k;
output_buffers 4 32k;
postpone_output 1460;
proxy_temp_path /tmp/nginx_proxy/;
client_body_in_file_only on;
log_format bytes_log "$msec $bytes_sent .";
include "/etc/nginx/vhosts/*";
}
With this domain specific file being included:-
server {
error_log /var/log/nginx/vhost-error_log warn;
listen x.x.x.x:x;
server_name songbanc.com www.songbanc.com;
access_log /usr/local/apache/domlogs/mydomain.com-bytes_log bytes_log;
access_log /usr/local/apache/domlogs/mydomain.com combined;
root /home/mydomain/public_html;
location / {
location ~.*\.(3gp|gif|jpg|jpeg|png|ico|wmv|avi|asf|asx|mpg|mpeg|mp4|pls|mp3|mid|wav|swf|flv|html|htm|txt|js|css|exe|zip|tar|rar|gz|tgz|bz2|uha|7z|doc|docx|xls|xlsx|pdf|iso)$ {
expires 7d;
try_files $uri #backend;
}
error_page 405 = #backend;
add_header X-Cache "HIT from Backend";
proxy_pass http://x.x.x.x:8081;
include proxy.inc;
}
location #backend {
internal;
proxy_pass http://x.x.x.x:8081;
include proxy.inc;
}
location ~ .*\.(php|jsp|cgi|pl|py)?$ {
proxy_pass http://x.x.x.x:8081;
include proxy.inc;
}
location ~ /\.ht {
deny all;
}
location ~* \.(mp3)$ {
expires max;
}
}
I believe the reason may be because your conf file was unnecessarily complex and errors start to creep into such configs.
location ~ .*\.(php|jsp|cgi|pl|py)?$ should be location ~ .*\.(php|jsp|cgi|pl|py)$.
The long nested if block under location / is similarly not required.
The add_header X-Cache directive should be in proxy.inc.
Named locations such as "#backend" do not need "internal" directives.
Anyway, after striping things down, we are left with:
server {
error_log /var/log/nginx/vhost-error_log warn;
listen x.x.x.x:x;
server_name songbanc.com www.songbanc.com;
access_log /usr/local/apache/domlogs/mydomain.com-bytes_log bytes_log;
access_log /usr/local/apache/domlogs/mydomain.com combined;
root /home/mydomain/public_html;
index index.html index.php;
error_page 418 = #backend;
location / {
expires 7d;
add_header Cache-Control "public";
try_files $uri $uri/ #backend;
}
location ~* \.mp3$ {
# Add rewrite rules to handle these requests here
add_header Cache-Control "public";
expires max;
}
location ~ .*\.(php|jsp|cgi|pl|py)$ {
return 418;
}
location #backend {
proxy_pass http://x.x.x.x:8081;
include proxy.inc;
}
location ~ /\.ht {
deny all;
}
}
This should have the static files cached and dynamic ones not cached. requires rewrite rules for the mp3 block to be translated from the backend.
Alternatively, you can just pass the mp3 requests to the backend.
server {
error_log /var/log/nginx/vhost-error_log warn;
listen x.x.x.x:x;
server_name songbanc.com www.songbanc.com;
access_log /usr/local/apache/domlogs/mydomain.com-bytes_log bytes_log;
access_log /usr/local/apache/domlogs/mydomain.com combined;
root /home/mydomain/public_html;
index index.html index.php;
error_page 418 = #backend;
location / {
expires 7d;
add_header Cache-Control "public";
try_files $uri $uri/ #backend;
}
location ~* \.mp3$ {
add_header Cache-Control "public";
expires max;
return 418;
}
location ~ .*\.(php|jsp|cgi|pl|py)$ {
return 418;
}
location #backend {
proxy_pass http://x.x.x.x:8081;
include proxy.inc;
}
location ~ /\.ht {
deny all;
}
}
I am not 100% certain if directives such as "expires" and "add_header" are not cleared when a redirect is triggered. If you find that you are not getting the you headers with the config above, this slightly longer one should do it.
server {
error_log /var/log/nginx/vhost-error_log warn;
listen x.x.x.x:x;
server_name songbanc.com www.songbanc.com;
access_log /usr/local/apache/domlogs/mydomain.com-bytes_log bytes_log;
access_log /usr/local/apache/domlogs/mydomain.com combined;
root /home/mydomain/public_html;
index index.html index.php;
error_page 418 = #backend;
location / {
expires 7d;
add_header Cache-Control "public";
try_files $uri $uri/ #backend;
}
location ~* \.mp3$ {
error_page 418 = #backend_alt;
return 418;
}
location ~ .*\.(php|jsp|cgi|pl|py)$ {
return 418;
}
location #backend {
proxy_pass http://x.x.x.x:8081;
include proxy.inc;
}
location #backend_alt {
proxy_pass http://x.x.x.x:8081;
include proxy.inc;
add_header Cache-Control "public";
expires max;
}
location ~ /\.ht {
deny all;
}
}