I'm fairly new to Nginx, and I'm working on converting an .htaccess file into something nginx can make sense of. Everything's working well (mostly) - I can pull up the homepage just fine. The problem is when I get to a post page.
think similar to wordpress, URLs like:
http://www.example.com/12/post-title-in-slug-form
Where 12 is the post id, and obviously that string is the post slug. I'm trying to parse those as two separate arguments (id & slug) and pass them into index.php like I was successfully doing in apache. I'm getting a 404 page, though, and have confirmed it is because of the rewriterule. Here's what the entire config file looks like, with only the website name changed (for privacy):
user www-data;
worker_processes 4;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
##
# nginx-naxsi config
##
# Uncomment it if you installed nginx-naxsi
##
#include /etc/nginx/naxsi_core.rules;
##
# nginx-passenger config
##
# Uncomment it if you installed nginx-passenger
##
#passenger_root /usr;
#passenger_ruby /usr/bin/ruby;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
server {
listen 80;
server_name example.com;
access_log off;
error_log on;
# deny access to .XYZ files
location ~ /\. {
return 403;
}
location ~ sitemap\.xml {
return 301 http://example.com/sitemap.php;
}
location ~ .php$ {
# Here you have to decide how to handle php
# Generic example configs below
# Uncomment and fix up one of the two options
# Option 1: Use FastCGI
fastcgi_index index.php;
include fastcgi_params;
fastcgi_pass unix:/var/run/php5-fpm.sock;
}
location / {
try_files $uri $uri/ #router;
}
location #router {
rewrite ^/([0-9]+)/?(.*)?/?$ /index.php?id=$1&slug=$2 last;
}
}
}
Please let me know if you can spot what's throwing it off when it comes to parsing the individual posts into ids and slugs and passing them. Thanks!
You should add a / in the beginning and a / before index.php like this :
rewrite ^/([0-9]+)/?(.*)?/?$ /index.php?id=$1&slug=$2 last;
Note i also used $1 and $2
If what you posted is indeed the COMPLETE config file, then the setup is missing something to handle PHP files as the regexp looks to be fine.
I actually think the config you posted cannot be the full one or that there is something fundamental going on as that config should have thrown errors and failed to load and also, since you mentioned that your PHP was loading fine, then it cannot be the posted config serving your website.
A better config is attached below:
FYI, try_files ABC XYZ last; is not valid syntax and you need at least two options in try_files. Anyway, fixed those in the posted config as well.
server {
listen 80;
server_name example.com;
access_log off;
error_log on;
# deny access to .XYZ files
location ~ /\. {
return 403;
}
location ~ sitemap\.xml {
return 301 http://example.com/sitemap.php;
}
location ~ .php$ {
# Here you have to decide how to handle php
# Generic example configs below
# Uncomment and fix up one of the two options
# Option 1: Use FastCGI
#fastcgi_index index.php;
#include fastcgi_params;
#fastcgi_pass unix:/var/run/php5-fpm.sock;
# Option 2: Pass to Apache
# Proxy_pass localhost:APACHE_PORT
}
location / {
try_files $uri $uri/ #router;
}
location #router {
rewrite ^/([0-9]+)/?(.*)/?$ /index.php?id=$1&slug=$2 last;
}
}
You will need to fix the PHP handling bit and choose which setup you want to implement.
I think though that you need to verify that you only have one instance of nginx running and that it is what is serving your site.
Related
I'm trying to configure an error page in nginx for 500 and 502 error codes, I tried many different configuration options and solutions but none of them worked for me.
The issue itself is, that no matter how I do the configuration, I always get the generic Nginx error page with 502 bad gateway.
The following docker stack is running with these containers:
Nginx
MySQL
Composer
Azure CLI
PHP
A TYPO3 system is running behind the php/composer container.
I'm using Nginx instead of a Apache web server.
Below you can see my current nginx configuration.
server {
listen 80;
root /var/www/html/public;
index index.php index.htm index.html;
# Make site accessible from http://localhost/
server_name _;
# Disable sendfile as per https://docs.vagrantup.com/v2/synced-folders/virtualbox.html
sendfile off;
error_log /dev/stdout info;
access_log /var/log/nginx/access.log;
# NGINX - Provide error page
error_page 500 502 /error.html;
location = /error.html {
internal;
}
## provide a health check endpoint
location /healthcheck {
access_log off;
stub_status on;
keepalive_timeout 0; # Disable HTTP keepalive
return 200;
}
location / {
absolute_redirect off;
try_files $uri $uri/ /index.php$is_args$args;
}
# pass the PHP scripts to FastCGI server listening on socket
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass ${PHP_DOMAIN}:9000;
fastcgi_buffers 16 128k;
fastcgi_buffer_size 128k;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_intercept_errors off;
# fastcgi_read_timeout should match max_execution_time in php.ini
fastcgi_read_timeout 600;
fastcgi_param SERVER_NAME $host;
fastcgi_cache_bypass $http_x_blackfire_query;
}
# Expire rules for static content
# Feed
location ~* \.(?:rss|atom)$ {
expires 1h;
}
# 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";
}
# Prevent clients from accessing hidden files (starting with a dot)
# This is particularly important if you store .htpasswd files in the site hierarchy
# Access to `/.well-known/` is allowed.
# https://www.mnot.net/blog/2010/04/07/well-known
# https://tools.ietf.org/html/rfc5785
location ~* /\.(?!well-known\/) {
deny all;
}
# Prevent clients from accessing to backup/config/source files
location ~* (?:\.(?:bak|conf|dist|fla|in[ci]|log|psd|sh|sql|sw[op])|~)$ {
deny all;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
# TYPO3 - Block access to composer files
location ~* composer\.(?:json|lock) {
deny all;
}
# TYPO3 - Block access to flexform files
location ~* flexform[^.]*\.xml {
deny all;
}
# TYPO3 - Block access to language files
location ~* locallang[^.]*\.(?:xml|xlf)$ {
deny all;
}
# TYPO3 - Block access to static typoscript files
location ~* ext_conf_template\.txt|ext_typoscript_constants\.(?:txt|typoscript)|ext_typoscript_setup\.(?:txt|typoscript) {
deny all;
}
# TYPO3 - Block access to miscellaneous protected files
location ~* /.*\.(?:bak|co?nf|cfg|ya?ml|ts|typoscript|dist|fla|in[ci]|log|sh|sql)$ {
deny all;
}
# TYPO3 - Block access to recycler and temporary directories
location ~ _(?:recycler|temp)_/ {
deny all;
}
# TYPO3 - Block access to configuration files stored in fileadmin
location ~ fileadmin/(?:templates)/.*\.(?:txt|ts|typoscript)$ {
deny all;
}
# TYPO3 - Block access to libaries, source and temporary compiled data
location ~ ^(?:vendor|typo3_src|typo3temp/var) {
deny all;
}
# TYPO3 - Block access to protected extension directories
location ~ (?:typo3conf/ext|typo3/sysext|typo3/ext)/[^/]+/(?:Configuration|Resources/Private|Tests?|Documentation|docs?)/ {
deny all;
}
if (!-e $request_filename) {
rewrite ^/(.+)\.(\d+)\.(php|js|css|png|jpg|gif|gzip)$ /$1.$3 last;
}
#Include development locations if needed
include /etc/nginx/conf.d/locations/*.conf;
}
I think the issue itself does not come from the configuration but from anywhere else but I don't know where.. I can't find the problem.
Hope u guys can help me, btw it's my first stack overflow question :D
EDIT:
Just added the configuration below to test the error codes but unfortunately I still get a 502 Bad Gateway, maybe a problem with the local setup. To my surprise the configured location for a healthcheck is working, just the error page not.
location /get_error {
return 500;
}
UPDATE:
The configuration itself was correct, I just deployed the changes made to the dev system and it just worked! I don't know why and where the issue was but it just won't work for my local dev environment.
This is a duplicate question, 100%. ...I have tried a great many solutions from other answers, which haven't worked. I searched for the errors with site:github.com, which may indicate it is a Laravel issue and not necessarily a PyroCMS 3 issue. I have searched here-- I found plenty of people that have asked the same question, but their answers just don't fix my problem.
My initial login after the install goes a lot like this:
"This form is not secure. Autofill has been turned off." Click!
"Send Anyway" Click!
Whoops! "The GET method is not supported for this route. Supported methods: POST." The sadness. No joy.
I am just not sure what to do.
Looking at other posts, I have cleared the cache with optimize:clear and the route cache. I am on about my tenth successful install-- sort of. I tried with PHP 8, which didn't work. I am trying with PHP 7.4 now. Just not sure quite what to do. I have specified my raw domain when prompted, I have specified domain.com:443 when prompted. ...I have to have gotten the passwords to match what I entered at least once.
Here is a youtube video:
https://youtu.be/LKxmxv6t07A
Edit: I know where the problem is!
My URLs are being generated as http://domain.tld/whatever, the code is autogenerating insecure URLs.
Here is the forgot password link as an example:
<a href="http://www.dibbsonit.com/users/password/forgot?redirect=%2F">
My Nginx site config:
# --------------------------
#
# Redirect non-www > www
#
# --------------------------
#server {
# listen 80;
# listen 443 ssl;
# server_name www.example.com;
# return 301 http://example.com$request_uri;
#}
# --------------------------
#
# Redirect to HTTP > HTTPS
#
# --------------------------
server {
# I generally like it the other way around, raw redirecting to the www subdomain.
# Regardless, that is something I will play with more later.
# if ($host = www.example.com) {
# return 301 https://$host$request_uri;
# } # managed by Certbot
# if ($host = example.com) {
# return 301 https://$host$request_uri;
# } # managed by Certbot
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
server {
# While I am spraying Whoops! messages...
# Just let people with my public IP address in.
# There is a similar whitelist feature in the pyrocms admin settings.
# allow 123.45.67.89;
# deny all;
# Listening on port 80 allows application level redirecting to SSL pages
listen 80;
listen 443 ssl;
server_name example.com www.example.com;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
index index.php index.html;
charset utf-8;
root /var/www/pyrocms/public;
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
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
gzip on;
gzip_static on;
gzip_http_version 1.0;
gzip_disable "MSIE [1-6].";
gzip_vary on;
gzip_comp_level 9;
gzip_proxied any;
gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
fastcgi_intercept_errors off;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
fastcgi_read_timeout 180;
# Remove trailing slashes
# This had to go. This was the main source of my boot loops.
# rewrite ^/(.*)/$ /$1 permanent;
# expires $expires;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# There are three places I know to change the "FORCE_SSL" setting:
# In the admin GUI (difficult to change if things go sideways)(the GUI updates the DB value).
# In the database under the table default_settings_settings directly.
# And as an environment variable here, subjectively the easiest place for me to manipulate it, if I needed to.
fastcgi_param FORCE_SSL true;
# fastcgi_param APP_URL https://example.com;
# fastcgi_param APPLICATION_URL https://example.com;
include fastcgi_params;
}
location ~ /\.ht {
access_log off;
log_not_found off;
deny all;
}
location ~* \.ico$ {
expires 1w;
access_log off;
}
location ~* \.(?:jpg|jpeg|gif|png|ico|gz|svg|svgz|ttf|otf|woff|eot|mp4|ogg|ogv|webm)$ {
try_files $uri $uri/ /index.php?$query_string;
access_log off;
log_not_found off;
}
location ~* \.(?:css|js)$ {
try_files $uri $uri/ /index.php?$query_string;
access_log off;
log_not_found off;
}
add_header "X-UA-Compatible" "IE=Edge,chrome=1";
}
I used the config file to specify that HTTPS should be forced. It is quick and easy if you have access to the file.
If you do it in the UI and something breaks in a way that prevents the application loading, you can go into the database and change the configuration value there. --But, that takes longer, for me anyways.
Im trying to move a drupal site I started on my localhost to a server at home. The database is both exported from my localhost and stored on the server.
The content of the nginx.conf file is as follows
events {
worker_connections 768;
# multi_accept on;
}
http{
server {
listen 443 ssl;
######## S S L CONFIGURATIONS ##################
ssl_certificate /etc/ssl/Nov2021/STAR_site.edu.co.crt;
ssl_certificate_key /etc/ssl/Nov2021/site.edu.co.key;
access_log /var/log/nginx/KNH_nginx.vhost.access.log;
error_log /var/log/nginx/KNH_nginx.vhost.error.log;
root /var/www/html/arctic_kittiwake;
index index.php index.html index.htm;
###################################################
server_name site.edu.co
location / {
#try_files $uri $uri/ /index.php?q=$uri&$args;
try_files $uri /index.php?q=$uri$args;
}
location /site/ {
if (!-e $request_filename){
rewrite ^/site/(.*)$ /site/index.php break;
}
}
location ~ \.php$ {
fastcgi_index index.php;
}
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
location ~ /\. {
deny all;
}
location ~* /(?:uploads|files)/.*\.php$ {
deny all;
}
}
}
The directory where this file is stored is the /etc/nginx and the drupal site is stored in the /var/www/html/arctic_kittiwake/ directory.
I also have php7.4-fpm and mariadb-10.3 installed.
You are missing connection with php-fpm.
Example:
# In Drupal 8, we must also match new paths where the '.php' appears in
# the middle, such as update.php/selection. The rule we use is strict,
# and only allows this pattern with the update.php front controller.
# This allows legacy path aliases in the form of
# blog/index.php/legacy-path to continue to route to Drupal nodes. If
# you do not have any paths like that, then you might prefer to use a
# laxer rule, such as:
# location ~ \.php(/|$) {
# The laxer rule will continue to work if Drupal uses this new URL
# pattern with front controllers other than update.php in a future
# release.
location ~ '\.php$|^/update.php' {
fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
# Ensure the php file exists. Mitigates CVE-2019-11043
try_files $fastcgi_script_name =404;
# Security note: If you're running a version of PHP older than the
# latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
# See http://serverfault.com/q/627903/94922 for details.
include fastcgi_params;
# Block httpoxy attacks. See https://httpoxy.org/.
fastcgi_param HTTP_PROXY "";
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param QUERY_STRING $query_string;
fastcgi_intercept_errors on;
# PHP 5 socket location.
#fastcgi_pass unix:/var/run/php5-fpm.sock;
# PHP 7 socket location.
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}
Full example is here https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/
You will have to bear with me here while I try and explain this the best I can.
I am working with a nginx server that I did not set up, I have very little knowledge of nginx. I have set up a new wordpress website which lives under the following url structure subsubdomain.subdomain.domain.com/website/ it is important that the full wordpress website is functional within the /website/ directory.
I have the site set up and the home page works perfectly when I navigate to subsubdomain.subdomain.domain.com/website/, but when I navigate to a subpage subsubdomain.subdomain.domain.com/website/resources/ the server throws File not found.
From my little knowledge of nginx I think this is a file permissions issue, I have logged into the server and run the following command sudo chmod 777 -R /path/to/website and also done sudo chown www:www -R /path/to/website to try and give full access. Unfortunately this has not worked either.
When checking the website access_log and error_log, they are empty. I then checked the nginx main log file and found the following error:
2018/05/31 04:07:42 [crit] 32426#0: *120 open() "/usr/share/nginx//var/www/sites-running/subsubdomain.subdomain.website.com/logs/nginx.access.log" failed (2: No such file or directory) while logging request, client: **.***.***.***, server: *.subdomain.domain.com, request: "GET /website/resources/ HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "subsubdomain.subdomain.domain.com", referrer: "http://subsubdomain.subdomain.domain.com/website/"
I'll be honest with you guys, this means nothing to me. All I can see is that it looks like the path to the log file is bad. So I went to my website nginx-vhost.conf file to see how it is defined and I have the following code:
access_log /var/www/sites-running/subsubdomain.subdomain.website.com/logs/nginx.access.log
Which looks all good to me.
So now I am stuck, I have no idea how to fix this so if anyone can make some sense of this and can help me out that would be amazing.
Cheers,
Luke.
UPDATE
I have just run nginx -V and noticed that there is a value called prefix, here is the value:
--prefix=/usr/share/nginx
It looks like this could be my problem but I have no idea what this is, how it is used and do not know the damage i could cause if I change it.
UPDATE
Here is my website nginx-vhost.conf file.
# Nginx configuration for Website
# This is for development purposes
server{
listen 80;
server_name subsubdomain.subdomain.domain.com;
set $site_root "/var/www/sites-available/$host";
set $public_html "$site_root/public_html";
set $logs_dir "$site_root/logs";
set $nginx_root "$site_root/webapps/ROOT";
root $nginx_root;
error_log /var/www/sites-available/subsubdomain.subdomain.domain.com/logs/nginx.error.log;
access_log /var/www/sites-available/subsubdomain.subdomain.domain.com/logs/nginx.access.log main;
index index.php;
#default_type text/html;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
#add_header 'Access-Control-Allow-Origin' "*";
# ------------------------------------------------------
#
# static resources routing for version control on assets
#
# ------------------------------------------------------
#location ~ ^/static/([^/]+)/(content|resources)/(.*)$ {
# alias $public_html/$2/$3;
#}
#location ~ ^/content/(.*)$ {
# alias $public_html/content/$1;
#}
location / {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/ /index.php?$args;
}
location /wp-admin {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/ /wp-admin/index.php?$args;
}
# ----------------------------------------
#
# PHP
#
# ----------------------------------------
location ~ \.php {
#NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
include /etc/nginx/fastcgi_params;
fastcgi_intercept_errors off;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SERVER_NAME $host;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param CONTENT_ROOT $public_html/content;
fastcgi_param CONTENT_UPLOAD_DIR $public_html/content;
fastcgi_param LOGS_ROOT $logs_dir;
fastcgi_param app.profile staging;
fastcgi_param APP_MODE staging;
fastcgi_param DB_NAME **********;
fastcgi_param DB_USER **********;
fastcgi_param DB_PASS **********;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}
Here is my main nginx.conf file
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log;
#error_log /var/log/nginx/error.log notice;
#error_log /var/log/nginx/error.log info;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
server_names_hash_bucket_size 128;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
client_max_body_size 100m;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
index index.html index.htm;
server {
listen 80 default_server;
server_name _;
root /usr/share/nginx/html;
#root /var/www/sites-running/nginx-default;
#index index.html index.htm;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
}
# redirect server error pages to the static page /40x.html
#
error_page 404 /404.html;
location = /40x.html {
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.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;
# root html;
# location / {
# }
#}
# HTTPS server
#
#server {
# listen 443;
# server_name localhost;
# root html;
# ssl on;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_timeout 5m;
# ssl_protocols SSLv2 SSLv3 TLSv1;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# }
#}
}
Thanks to everyone for their help. I have finally managed to figure out what was going wrong. I needed to update my conf file to have a second location statement which looked inside of the /website/ folder.
like so:
location /website/ {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/website/ /website/index.php?$args;
}
Here is my full nginx-vhost.conf file:
# Nginx configuration for Website
# This is for development purposes
server{
listen 80;
server_name subsubdomain.subdomain.domain.com;
set $site_root "/var/www/sites-available/$host";
set $public_html "$site_root/public_html";
set $logs_dir "$site_root/logs";
set $nginx_root "$site_root/webapps/ROOT";
root $nginx_root;
error_log /var/www/sites-available/subsubdomain.subdomain.domain.com/logs/nginx.error.log;
access_log /var/www/sites-available/subsubdomain.subdomain.domain.com/logs/nginx.access.log main;
index index.php;
#default_type text/html;
location = /favicon.ico {
log_not_found off;
access_log off;
}
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
#add_header 'Access-Control-Allow-Origin' "*";
# ------------------------------------------------------
#
# static resources routing for version control on assets
#
# ------------------------------------------------------
#location ~ ^/static/([^/]+)/(content|resources)/(.*)$ {
# alias $public_html/$2/$3;
#}
#location ~ ^/content/(.*)$ {
# alias $public_html/content/$1;
#}
location /website/ {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/website/ /website/index.php?$args;
}
location / {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/ /index.php?$args;
}
location /wp-admin {
# This is cool because no php is touched for static content.
# include the "?$args" part so non-default permalinks doesn't break when using query string
try_files $uri $uri/ /wp-admin/index.php?$args;
}
# ----------------------------------------
#
# PHP
#
# ----------------------------------------
location ~ \.php {
#NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
include /etc/nginx/fastcgi_params;
fastcgi_intercept_errors off;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SERVER_NAME $host;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param CONTENT_ROOT $public_html/content;
fastcgi_param CONTENT_UPLOAD_DIR $public_html/content;
fastcgi_param LOGS_ROOT $logs_dir;
fastcgi_param app.profile staging;
fastcgi_param APP_MODE staging;
fastcgi_param DB_NAME **********;
fastcgi_param DB_USER **********;;
fastcgi_param DB_PASS **********;;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}
I was able to set up nginx server blocks as per tutorials. When I try to access the sites through the respective domain names I am directed to the same site.
I have been trying to multiple the subsite of /site1 under localhost in windows.
nginx.conf
#user nobody;
# worker_processes 1;
worker_processes auto;
# error_log logs/error.log;
# error_log logs/error.log notice;
# error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
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 H:\www\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 H:\www\html;
}
# this is the default server
location = /site1 {
return 301 /site1/;
}
location ^~ /site1/ {
root H:\www\html\drupal-8.1.10;
index index.php;
}
location ~ /site1/\.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9123;
fastcgi_index index.php;
include fastcgi_params;
}
}
}
www directory:
H:\www\html>tree /f
Folder PATH listing for volume 975
Volume serial number is 0000-043C
H:.
│ 50x.html
│ index.html
│ drupal.tar.gz
│
└───drupal-8.1.10
index.php
The potential URL should be:
localhost
localhost/site1
Thanks
In Windows use:
nginx path on the same drive e.g:
H:/nginx
pid full absolute path e.g:
pid H:/nginx/logs/nginx.pid;
error logs enable e.g (uncoment):
error_log logs/error.log;
error_log logs/error.log notice;
error_log logs/error.log info;
set|enable output log format
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
correct root into server block is (in double ""):
server{
location /{
root "H:/nginx/www/html";
}
}
correct php fastCGI params e.g:
server{
location ~ /site1/\.php$ {
root www/html/site1
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME C:/nginx/www/html/site1$fastcgi_script_name;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
include fastcgi_params;
}
}
Well I think that's it.
All root settings must be enclosed in double quotes and normal bar (/) do not forget to see the log of errors ... it says a lot :)
My sample configuration:
init.bat (to start|close service)[can not serve you]
#ECHO OFF
TITLE LOCALHOST SERVICE
REM GO TO NGINX DIR
CD C:/nginx
TASKLIST /FI "IMAGENAME eq nginx.exe" | FIND /I "nginx.exe" > NUL && (GOTO STOP) || (GOTO START)
:START
ECHO.
ECHO ---------------------------- STARTING NGINX SERVER ----------------------------
ECHO.
REM START NGINX SERVICE
START/MIN nginx.exe
ECHO.
ECHO ----------------------------- STARTER PHP SERVICE -----------------------------
ECHO.
REM START PHP SERVICE (FOR NGINX)
php/php-cgi.exe -b 127.0.0.1:9000 -c C:/nginx/php/php.ini
REM GO TO "END" BLOCK FOR DON'T EXECUTE "STOP" BLOCK ¬¬
GOTO END
:STOP
REM QUIT|STOP NGINX SERVICE
REM OLD-COMMAND: START nginx.exe -s quit
TASKKILL /F /IM nginx.exe > NUL
REM STOP PHP SERVICE
TASKKILL /F /IM php-cgi.exe > NUL
GOTO END
:END
Ok the init.bat file lets you start or stop nginx and php with just a double-click simple.
You can add it there someone icon and place it in such work area.
Assuming php run in a subdirectory nginx would have the following structure:
// System hard drive (in my case)
---C:
| // nginx path
|--------nginx
|
|---nginx.exe //executable
|
|---conf // configurations path
|
|---logs // logs path
|
|---pid // path to pid your proccess
|
|---html // path to your server (or blocks)
|
|---mime.types // archive list mime types
|
|---init.bat // optinal
A good practice is to use server-blocks even if they do not use subdomains.
For this create a folder in "C:/nginx/conf" called "sites-enabled" and make a "backup" of your nginx configuration file "C:/nginx/conf/nginx.conf" for such "nginx.conf.bk".
The new configuration file would look like this:
nginx.conf (modified)
# Configuration File - Nginx Server Configs
# http://nginx.org/en/docs/dirindex.html
# Run as a unique, less privileged user for security reasons.
# user www www;
# Sets the worker threads to the number of CPU cores available in the system for best performance.
# Should be > the number of CPU cores.
# Maximum number of connections = worker_processes * worker_connections
worker_processes auto;
# Maximum number of open files per worker process.
# Should be > worker_connections.
worker_rlimit_nofile 8192;
events {
# If you need more connections than this, you start optimizing your OS.
# That's probably the point at which you hire people who are smarter than you as this is *a lot* of requests.
# Should be < worker_rlimit_nofile.
worker_connections 8000;
}
# Log errors and warnings to this file
# This is only used when you don't override it on a server{} level
error_log logs/error.log warn;
# The file storing the process ID of the main process
pid C:/nginx/pids/nginx.pid;
http {
# Hide nginx version information.
server_tokens off;
# Specify MIME types for files.
include mime.types;
default_type application/octet-stream;
# Update charset_types to match updated mime.types.
# text/html is always included by charset module.
charset_types text/css text/plain text/vnd.wap.wml application/javascript application/json application/rss+xml application/xml;
# Include $http_x_forwarded_for within default format used in log files
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# Log access to this file
# This is only used when you don't override it on a server{} level
access_log logs/access.log main;
# How long to allow each connection to stay idle.
# Longer values are better for each individual client, particularly for SSL,
# but means that worker connections are tied up longer.
keepalive_timeout 20s;
# Speed up file transfers by using sendfile() to copy directly
# between descriptors rather than using read()/write().
# For performance reasons, on FreeBSD systems w/ ZFS
# this option should be disabled as ZFS's ARC caches
# frequently used files in RAM by default.
sendfile on;
# Don't send out partial frames; this increases throughput
# since TCP frames are filled up before being sent out.
tcp_nopush on;
# Enable gzip compression.
gzip on;
# 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 256;
# 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/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;
# text/html is always compressed by gzip module
# This should be turned on if you are going to have pre-compressed copies (.gz) of
# static files available. If not it should be left off as it will cause extra I/O
# for the check. It is best if you enable this in a location{} block for
# a specific directory, or on an individual server{} level.
# gzip_static on;
# Include files in the sites-enabled folder. server{} configuration files should be
# placed in the sites-available folder, and then the configuration should be enabled
# by creating a symlink to it in the sites-enabled folder.
# See doc/sites-enabled.md for more info.
include C:/nginx/conf/sites-enabled/*.conf;
}
Note that the end of this example we "including" all files ".conf" of "sites-enabled" folder.
If you do not use server-blocks you can simply create a file "default.conf" that will have your server settings.
Something like this:
default.conf (example)
server {
listen 80;
keepalive_timeout 300s;
# define path to this project
root "C:/nginx/html/your_path_here";
# Specify a charset
charset utf-8;
# define your server name
server_name localhost;
index index.php index.html;
autoindex off;
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 ------------------------------
#
location ~ \.php$ {
# root for PHP FASTCGI MAPING
root html/your_path_here;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME C:/nginx/html/your_path_here$fastcgi_script_name;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
include fastcgi_params;
}
# Prevent clients from accessing hidden files (starting with a dot) -------------------
# This is particularly important if you store .htpasswd files in the site hierarchy
# Access to `/.well-known/` is allowed.
# https://www.mnot.net/blog/2010/04/07/well-known
# https://tools.ietf.org/html/rfc5785
location ~* /\.(?!well-known\/) {
deny all;
}
# Prevent clients from accessing to backup/config/source files ------------------------
location ~* (?:\.(?:bak|conf|dist|fla|in[ci]|log|psd|sh|sql|sw[op])|~)$ {
deny all;
}
# Expire rules for static content -----------------------------------------------------
# No default expire rule. This config mirrors that of apache as outlined in the
# html5-boilerplate .htaccess file. However, nginx applies rules by location,
# the apache rules are defined by type. A consequence of this difference is that
# if you use no file extension in the url and serve html, with apache you get an
# expire time of 0s, with nginx you'd get an expire header of one month in the
# future (if the default expire rule is 1 month). Therefore, do not use a
# default expire rule with nginx unless your site is completely static
# cache.appcache, your document html and data -----------------------------------------
location ~* \.(?:manifest|appcache|html?|xml|json)$ {
expires -1;
access_log logs/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";
}
# WebFonts ----------------------------------------------------------------------------
# If you are NOT using cross-domain-fonts.conf, uncomment the following directive
# location ~* \.(?:ttf|ttc|otf|eot|woff|woff2)$ {
# expires 1M;
# access_log off;
# add_header Cache-Control "public";
# }
}
For local development is a good choice to set cache negatito (-1) to always update to load the page.
Note that the configuration shown here is just an example and you may (or may not) use them.
Also note that by defining a root directory I put "your_path_here" replace as your real directory name.
This directory must be inside the folder "html" in "C:/nginx/html/".
To create a server-block to "site1" create a new configuration file in "sites-enabled" with any name and point to the corresponding root directory, this assuming your hosts file ("C:/Windows/System32/drives/etc/") has "site1" to "127.0.0.1" or subdomain is set to localhost (127.0.0.1 site1.localhost)
i Use
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME C:/nginx-0.7.60/html$fastcgi_script_name; #this is the one line for edition
include fastcgi_params;
}
C:\PHP5\php-cgi.exe -b 127.0.0.1:9000