Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
One of the major benefits of React (and Create React App) is that you don't need the overhead of running a Node server (or proxying to it with Nginx); you can serve the static files directly.From theDeployment documentationyou've linked to, Create React App describes what to do:npm run buildcreates abuilddirectory with a production build of your app. Set up your favorite HTTP server so that a visitor to your site is servedindex.html, and requests to static paths like/static/js/main..jsare served with the contents of the/static/js/main..jsfile.In your case, runnpm run buildto create thebuild/directory and then make the files available in a location Nginx can access them. Your build is probably best done on your local machine and then you can securely copy the files across to your server (via SCP, SFTP etc). Youcouldrunnpm run buildon your server, but if you do, resist the temptation to directly serve thebuild/directory as the next time you run a build, clients could receive an inconsistent set of resources whilst you're building.Whichever build method you choose, once yourbuild/directory is on your server, then check its permissions to ensure Nginx can read the files and configure yournginx.conflike so:server {
listen 80;
server_name app.mydomain.com;
root /srv/app-name;
index index.html;
# Other config you desire (TLS, logging, etc)...
location / {
try_files $uri /index.html;
}
}This configuration is based upon your files being in/srv/app-name. In short, thetry_filesdirective attempts to load CSS/JS/images etc first and for all other URIs, loads theindex.htmlfile in your build, displaying your app.For note, you should be deploying using HTTPS/SSL to serve it rather than with insecure HTTP on port 80.Certbotprovides automatic HTTPS for Nginx with free Let's Encrypt certificates, if the cost or process of obtaining a certificate would otherwise hold you back. | I'm attempting to deploy mycreate-react-appSPA on a Digital Ocean droplet with Ubuntu 14.04 and Nginx. Per the static serverdeployment instructions, I can get it working when I runserve -s build -p 4000, but the app comes down as soon as I close the terminal. It is not clear to me from thecreate-react-apprepo readme how to keep it running forever, similar to something likeforever.Without runningserve, I get Nginx's 502 Bad Gateway error.Nginx Confserver {
listen 80;
server_name app.mydomain.com;
root /srv/app-name;
index index.html index.htm index.js;
access_log /var/log/nginx/node-app.access.log;
error_log /var/log/nginx/node-app.error.log;
location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm|svg)$ {
root /srv/app-name/build;
}
location / {
proxy_pass http://127.0.0.1:4000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Access-Control-Allow-Origin *;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
} | Deploy Create-React-App on Nginx |
Try changing the command asdocker run --rm --gpus all --platform linux/amd64 -v static_volume:/home/app/staticfiles/ -v media_volume:/app/uploaded_videos/ --name=deepfakeapplication abhijitjadhav1998/deefake-detection-20framemodelPlease ensure that you have compatible Nvidia Drivers available as this application uses Nvidia CUDA. | WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
docker: Error response from daemon: could not select device driver "" with capabilities: [[gpu]].I am facing this error on mac while trying to run this commanddocker run --rm --gpus all -v static_volume:/home/app/staticfiles/ -v media_volume:/app/uploaded_videos/ --name=deepfakeapplication abhijitjadhav1998/deefake-detection-20framemodelHow to solve this error? | WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) |
You've fixed the issue on your HTTP server, but your HTTP server is set to 301 redirect to your HTTPS server... your HTTPS server does not haveclient_max_body_sizeconfigured, so it is defaulting to 1M & causing this413 (Request Entity Too Large)error.To fix this issue, you simply need to addclient_max_body_sizetoBOTHthe HTTP server blockandthe HTTPS server block, as shown in the example below:http {
...
######################
# HTTP server
######################
server {
...
listen 80;
server_name xxxx.net;
client_max_body_size 100M;
...
}
######################
# HTTPS server
######################
server {
...
listen 443 default_server ssl;
server_name xxxx.net;
client_max_body_size 100M;
...
}
}More info onclient_max_body_sizehere:http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_sizeSyntax: client_max_body_size size;Default: client_max_body_size 1m;Context: http, server, locationSets the maximum allowed size of the client request body, specified in
the “Content-Length” request header field. If the size in a request
exceeds the configured value, the 413 (Request Entity Too Large) error
is returned to the client. Please be aware that browsers cannot
correctly display this error. Setting size to 0 disables checking of
client request body size.Read More about configuring HTTPS servers here:http://nginx.org/en/docs/http/configuring_https_servers.html | I am making a practice web service (client's artbook display web site) The client can upload artbook images to the server.But I get the following error when the client uploads too many images413 Request Entity Too LargeI tried addingclient_max_body_size 100M;in nginx.conf#user nobody;
#Defines which Linux system user will own and run the Nginx server
worker_processes 1;
#error_log logs/error.log; #error_log logs/error.log notice;
#Specifies the file where server logs.
#pid logs/nginx.pid;
#nginx will write its master process ID(PID).
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#access_log logs/access.log main;
sendfile on;
server {
listen 80;
server_name xxxx.net;
client_max_body_size 100M;
keepalive_timeout 5;
return 301 https://$server_name$request_uri;
}
# HTTPS server
#
server {
listen 443 default_server ssl;
server_name xxx.net;
ssl_certificate /etc/letsencrypt/live/xxxx.net/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/xxxx.net/privkey.pem;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header HOST $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:8000;
proxy_redirect off;
}
}
}and tried:sudo service nginx restart
sudo service nginx reloadand retryrunserverbut still get413 Request Entity Too LargeCan anybody help? | 413 Request Entity Too Large nginx django |
commandoverrides the default command.That's the reason your container stops: nginx never starts.At the end of your script you have to runnginx#!/bin/bash
echo running post install scripts for web..;
cd /srv/myweb
npm install
composer self-update
composer update
nginxBy the way, I suggest you to change your script and runnpm installandcomposer *updateonly if required (thus only if some file in /src/myweb does not exists), because it makes your container startup time increase in vain.Note that by doing so, NginX will never catch the SIGTERM signal sent by docker stop. That can cause it to be abruptly killed.Instead, if you want to be sure that SIGTERM is received by nginx, you have to replace the last line withexec nginx. This replaces the bash process with nginx itself. | I want to run a script, right after running`docker-compose up -d`Here is my snippet ofdocker-compose.yml. The other settings are mysql server, redis...etc....but they are not causing any problemsweb:
image: nginx
container_name: web-project
volumes:
- ./code:/srv
working_dir: /srv/myweb
extra_hosts:
- "myweb.local:127.0.0.1"
ports:
- 8081:80
# tty: true
command: sh /srv/scripts/post-run-web.shSo whenever i rundocker-compose up -dordocker-compose upIt all stops. (the containers do not keep running). Although my shell script is simple (running echos...or phpunit). Here is my script.#!/bin/bash
echo running post install scripts for web..;
cd /srv/myweb
npm install
composer self-update
composer updateAnd this is the error I get. It is like the server (nginx) is not running yet. Also if I connect to the server using exec bash, and i check out the processes. I do not see nginx running (yet).web_1 | You are already using composer version 7a9eb02190d334513e99a479510f87eed18cf958.
web_1 | Loading composer repositories with package information
web_1 | Updating dependencies (including require-dev)
web_1 | Generating autoload files
web-project exited with code 0
Gracefully stopping... (press Ctrl+C again to force)
Stopping mysql-project... done
Stopping rabbitmq-project... done
Stopping redis-project... doneSo why is it exiting, although the script is syntax-wise correct? How can i make it run correctly? (what am I doing, setting up wrong!) | docker-compose yml running a script after up |
I found help in the nginx irc chat.Basically what I needed to do was use a return instead of rewrite. So I changed this:location = / {
rewrite "^$" /wiki/Main_Page;
}to this:location = / {
return 301 http://www.example.com/wiki/Main_Page;
} | I'm converting my mediawiki site to use nginx as a frontend for static files with apache on the backend for php. I've gotten everything working so far except for when I view the root directory "example.com" it tries to serve a directory listing and gives a 403 error since I have that disabled and don't have an index file there.The apache rewrite rule I have in place right now is simply:RewriteRule ^$ /wiki/Main_Page [L]I tried something similar with a location directive in nginx, but it's not working:location = / {
rewrite "^$" /wiki/Main_Page;
}The rest of my location directives are:location / {
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite ^/wiki/(.*)$ /w/index.php?title=$1&$args;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
try_files $uri /w/index.php?title=$1&$args;
expires max;
log_not_found off;
}
location ~ \.php?$ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
proxy_pass http://127.0.0.1:8080;
}I can simply put an index.php file with header('Location:') in it, but I'd rather just do it properly with a rewrite rule.All the examples I've found online for running mediawiki with nginx run the wiki as wiki.example.com instead of a /wiki/ subdirectory.Edit: I also tried adding to the try_files like this:try_files $uri $uri/ @rewrite /wiki/Main_Page;with the same 403 error result. | Rewrite root address to a subdirectory in nginx |
Since you have a::1 localhostline in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.Since the web server is not listening on IPv6, the connection fails.You could try to use the--ipv4option tocurl, which should force an IPv4 connection when both are available. | My host's file maps127.0.0.1tolocalhost.$ curl -I 'localhost'
curl: (7) Failed to connect to localhost port 80: Connection refusedAnd then$ curl -I 127.0.0.1
HTTP/1.1 200 OK
Server: nginx/1.2.4
Date: Wed, 09 Apr 2014 04:20:47 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 23 Oct 2012 21:48:34 GMT
Connection: keep-alive
Accept-Ranges: bytesIn my host's file I have127.0.0.1 localhostIt appears that thecurlcommand fails to recognize entries in/etc/hosts. Can someone explain why?update:I've yet to try this but I've discovered you can configurenginx to respond to ipv4 and ipv6 | curl Failed to connect to localhost port 80 |
The add_header trick is how I would do it to.I'm at work right now, so I can't test but you might possibly get something in the logfile i you set theerror_loglevel to:debug: you're nginx needs to be built using--with-debugfor this to work, you can check that with thenginx -Vcommandnotice: if debug logging isn't enabled | I'm wondering how do I know if a particular location[s] used to process request innginx.E.g.:# 1
location / {}
# 2
location ~ /[\w\-]+\.html {}
# 3
location ~ /\w+\.html {}How do I know if URI like/mysiteis processed by 3rd location and not 2nd?
I tend to useadd_headerfor this matter:location / {
add_header location 1;
}
location ~ /(\w+\-)\.html {
add_header location 2;
}
location @named {
add_header location named;
}And I'd like to know is there a better solution or what do you personally use for debugging purposes? | nginx. Test which location used to process request |
You can match the different URLs withserver {}blocks, then inside each server block, you'd have the reverse proxy settings.Below, an illustration;server {
server_name client.example.com;
# app1 reverse proxy follow
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://x.x.x.100:80;
}
server {
server_name client2.example.com;
# app2 reverse proxy settings follow
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://x.x.x.101:80;
}Also, you may add further Nginx settings (such aserror_pageandaccess_log) as desired in eachserver {}block. | Here is my situation: I will have one frontend server running Nginx, and multiple backends servers running Apache + passenger with different rails applications. I am NOT trying to do any load balancing. What I need to do is setup Nginx to proxy connections to specific servers based on the URL. IE,client.example.comshould point tox.x.x.100:80,client2.example.comshould point tox.x.x.101:80, etc.I am not that familiar with Nginx, but I could not find a specific configuration online that fit my situation. | Nginx reverse proxy multiple backends |
in Chrome and Safari you need to useContent-Security-PolicyContent-Security-Policy: frame-ancestors domain.comYou can check more details on this site:https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives | Im trying to set the ALLOWED-FROM in Nginx but all settings I tried so far resulted in the following Chrome error:Invalid 'X-Frame-Options' header encountered when loading 'https://domain.com/#/register': 'ALLOW-FROM domain.com' is not a recognized directive. The header will be ignored.This options I tried are those: (tried also with FQDN withhttps://prefix)add_header X-Frame-Options "Allow-From domain.com";
add_header X-Frame-Options "ALLOW-FROM domain.com";
add_header X-Frame-Options "ALLOW-FROM: domain.com";
add_header X-Frame-Options "Allow-From: domain.com";
add_header X-Frame-Options ALLOW-FROM "domain.com";
add_header X-Frame-Options ALLOW-FROM domain.com; | How to set X-Frame-Options Allow-From in nginx correctly |
I found the way to do this:http://nginx.org/en/docs/http/ngx_http_sub_module.htmllocation / {
sub_filter
'';
sub_filter_once on;
} | Is there a way to inject a few lines of script etc. for each served php/html/etc. page?
For example some custom javascript after -tag?I know, you should be able to use lua in nginx but is there a better solution?I am running multiple different web application behind the nginx, so it feels proper way to do this. I don't have access source code for each application and maintaining those would be cumbersome. | How to inject custom content via Nginx? |
You have to use theproxy_redirectto handle the redirection.Sets the text that should be changed in the “Location” and “Refresh” header fields of a
proxied server response. Suppose a proxied server returned the header field
“Location:https://myserver/uri/”. The directive
will rewrite this string to “Location: http://nginx_server:8080/uri/”.Example:proxy_redirect https://myserver/ http://nginx_server:8080/;Source:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_redirect | I want to set up Nginx as a reverse proxy for a https service, because we have a special usecase where we need to "un-https" a connection:http://nginx_server:8080/myserver ==> https://mysecureserviceBut what happens is that the actual https service isn't proxied. Nginx does redirect me to the actual service, so the URL in the browser changes. I want to interact with Nginx as it was the actual service, just without https.This is what I have:server {
listen 0.0.0.0:8080 default_server;
location /myserver {
proxy_pass https://myserver/;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
}
} | Nginx does redirect, not proxy |
Found a solution using nginx named locations:location = / {
add_header Cache-Control no-cache;
expires 0;
try_files /index.html =404;
}
location / {
gzip_static on;
try_files $uri @index;
}
location @index {
add_header Cache-Control no-cache;
expires 0;
try_files /index.html =404;
} | I'm serving Angular 2 application with nginx using location section this way:location / {
try_files $uri $uri/ /index.html =404;
}try_files directive tries to find the requested uri in root directory and if it fails to find one it simply returns index.htmlHow to disable caching of index.html file? | Disable caching of a single file with try_files directive |
I got it.location ~ ^/$ {
return 301 https://www.b.com/;
} | I only want to redirect the root path from domain A to domain B. For example, if user type inhttps://www.a.com/orhttps://www.a.comorhttp://a.comall redirect tohttps://www.b.com/, but if user type inhttps://www.a.com/something/then it keep there without redirect.I tried the following:location / {
return 301 https://www.b.com/;
}but it redirect all to www.b.com even user type inhttps://www.a.com/something/. | How to redirect only the root path in nginx? |
Well I guess I don't really need the outer "if" statement since I'm only checking for domains of the form xxx.xxx anyways. The following works for me, though it's not robust. Let me know if there is a better solution.if ($host ~* ^([a-z0-9\-]+\.(com|net|org))$) {
set $host_with_www www.$1;
rewrite ^(.*)$ http://$host_with_www$1 permanent;
}Edit: Added hyphen to the regular expression since it is a valid character in a hostname. | I see the NginxHttpRewriteModule documentationhas an example to rewrite a www-prefixed domain to a non-www-prefixed domain:if ($host ~* www\.(.*)) {
set $host_without_www $1;
rewrite ^(.*)$ http://$host_without_www$1 permanent; # $1 contains '/foo', not 'www.mydomain.com/foo'
}How can I do the reverse-- rewrite a non-www-prefixed domain to a www-prefixed domain? I thought maybe I could do something like the following but Nginx doesn't like the nested if statement.if ($host !~* ^www\.) { # check if host doesn't start with www.
if ($host ~* ([a-z0-9]+\.[a-z0-9]+)) { # check host is of the form xxx.xxx (i.e. no subdomain)
set $host_with_www www.$1;
rewrite ^(.*)$ http://$host_with_www$1 permanent;
}
}Also I wanted this to work for any domain name without explicitly telling Nginx to rewrite domain1.com -> www.domain1.com, domain2.com -> www.domain2.com, etc. since I have a large number of domains to rewrite. | Nginx rewrite non-www-prefixed domain to www-prefixed domain |
I had the exactly same problem and spent a couple of hours...
I guess you are using older version of nginx (lower than 1.7)?
In nginx 1.7 you can usethis directive:proxy_ssl_server_name on;This will force nginx to useSNIAlso, you should set the SSL protocols:proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2;For earlier versions you may be able to use this patch (but I can't verify that that is working):http://trac.nginx.org/nginx/ticket/2292019 Update: You should avoid TLSv1 and TLSv1.1 and disable them if possible. I'll leave them in the answer as they are still valid for SNI. | NGINX acting as a caching proxy encounters problems when fetching content from CloudFront server over HTTPS:This is the extract from the NGINX's error log:2014/08/14 16:08:26 [error] 27534#0: *11560993 SSL_do_handshake() failed (SSL: error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure) while SSL handshaking to upstream, client: 82.33.49.135, server: localhost, request: "GET /static/images/media-logos/best.png HTTP/1.1", upstream: "https://x.x.x.x:443/static/images/media-logos/best.png",I tried different proxy setting like proxy_ssl_protocols and proxy_ssl_ciphers but no combination worked.Any ideas? | NGINX caching proxy fails with SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure |
Nginx is a web server and puma is an application server.
Both have their advantages, and you need both.Some examples:Static redirects- you could setup your nginx to redirect allhttptraffic to the same url withhttps. This way such trivial requests will never hit your app server.Multipart upload- Nginx is better suited to handle multipart uploads. Nginx will combine all the requests and send it as a single file to puma.Serving static assets- It is recommended to serve static assets (those in/public/endpoint in rails) via a webserver without loading your app server.There are some basic DDoS protections built-in in nginx. | I'm deploying a Rails app to production. It seems that Puma is fast and handles many of the things I want in a web server.I'm wondering if I even need to bother with Nginx, and what I'd be missing out on if just used Puma? | Why do I need Nginx with Puma? |
I think I will go forward with Nginx module devlopmenthttp://www.evanmiller.org/nginx-modules-guide.htmlWhy ?It don't require any other library dependency like fastcgi and
other.I can use all feature of nginx inside my module. | I need to write a C++ interface that can read our data structure and provide the o/p based on query using http protocol.Server NeedIt should be able to serve 100 clients at the same time.Why C++All code is already written in C++. So we need to just write a http layer in C++. That's why I am choosing C++ instead of a more conventional web-programming language.I am thinking to use nginx to serve static files and use its proxy pass to communicate with C++.There are two approaches I have found:Write a FastCGI c++ module.Write a node.js c++ module.Please just any other suggestion if you haveCan you please list the pros and cons for each method based on prior experience? | Best method to create a c++ app to communicate with nginx |
I also needed to modify the nginx configuration.Create a script that modifies the nginx configuration (probably you want/etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker.conf) and restarts the nginx service (service nginx restart).You need to execute that script after this nginx config file is written which is after normal ebextensions are executed. This is undocumented, but Evan shared how to do thishere: essentially you use an ebextension to copy the script into a directory with hooks that gets executed at the proper time.An example ebextension config is.ebextensions/01modify_nginx.config:container_commands:
copy:
command: "cp .ebextensions/01rewrite_nginx_config.py /opt/elasticbeanstalk/hooks/appdeploy/enact/"
make_exe:
command: "chmod +x /opt/elasticbeanstalk/hooks/appdeploy/enact/01rewrite_nginx_config.py"This is working nicely now for my project (hereis the source where you can see it in action). | After i login and the cookie is set I get error 502. When i read the log i get the error:014/05/17 01:54:43 [error] 11013#0: *8 upstream sent too big header while reading response
header from upstream, client: 83.248.134.236, server: , request: "GET /administration
HTTP/1.1", upstream:After some fast googling i found:http://developernote.com/2012/09/how-i-fixed-nginx-502-bad-gateway-error/and I want to try to set fastcgi_buffers and fastcgi_buffer_size to a different value.
But how do i set variable on nginx in amazon elasticbeanstalk?The nginx server is before my docker instance. | How to change nginx config in amazon elastic beanstalk running a docker instance |
It's not very complicated from a conceptual point of view. I'll try to be clear but I have to do some simplification.The event based servers (likenginxandlighttpd) use a wrapper around an event monitoring system. For example. lighttpd useslibeventto abstract the more advanced high-speed event monitoring system (seelibevalso).The server keeps track of all the non blocking connections it has (both writing and reading) using a simple state machine for each connection. The event monitoring system notifies the server process when there is new data available or when it can write more data. It's like aselect()on steroids, if you know socket programming. The server process then simply sends the requested file using some advanced function likesendfile()where possible or turns the request to a CGI process using a socket for communication (this socket will be monitored with the event monitoring system like the other network connections.)Thislink as a lot of great information about the internals of nginx, just in case. I hope it helps. | I'm trying to understand what makes Nginx so fast, and I have a few questions.As I understand it, Apache either spawns a new process to serve each request OR spawns a new thread to serve each request. Since each new thread shares virtual address space the memory usage keeps climbs if there are a number of concurrent requests coming in.Nginx solves this by having just one listening process(Master), with a single execution thread AND 2 or 3(number is configurable) worker processes. This Master process/thread is running an event loop. Effectively waiting for any incoming request. When a request comes in it gives that request to one of the worker processes.Please correct me if my above understanding is not correctIf the above is correct, then I have a few questions:Isn't the worker process going to spawn multiple threads and going to run into the same problem as apache ?Or is nginx fast because its event based architecture uses nonblocking-IO underneath it all. Maybe the worker process spawns threads which doonlynon-blocking-IO, is that it ?What "exactly" is "event based architecture", can someone really simplify it, for soemone like me to understand. Does it just pertain to non-blocking-io or something else as well ?I got a reference ofc10k, I am trying to go through it, but I don't think its about event based arch. it seems more for nonblocking IO. | nginx : Its Multithreaded but uses multiple processes? |
You cannot useproxy_passin if block, so I suggest to do something like this before setting proxy header:set $my_host $http_host;
if ($http_host = "beta.example.com") {
set $my_host "www.example.com";
}And now you can just useproxy_passandproxy_set_headerwithout if block:location / {
proxy_pass http://rubyapp.com;
proxy_set_header Host $my_host;
} | I am running nginx as reverse proxy for the site example.com to loadbalance a ruby application running in backend server. I have the followingproxy_set_headerfield in nginx which will pass host headers to backend ruby. This is required by ruby app to identify the subdomain names.location / {
proxy_pass http://rubyapp.com;
proxy_set_header Host $http_host;
}Now I want to create an aliasbeta.example.com, but the host header passed to backend should still bewww.example.comotherwise the ruby application will reject the requests. So I want something similar to below inside location directive.if ($http_host = "beta.example.com") {
proxy_pass http://rubyapp.com;
proxy_set_header Host www.example.com;
}What is the best way to do this? | Change Host header in nginx reverse proxy |
Since your location alias end match, you should just use root. Also, noteverythingis routed through index.php on wordpress afaik. Also, unless you know you need path info, you probably dont. I think you want something like:location @wp {
rewrite ^/wordpress(.*) /wordpress/index.php?q=$1;
}
location ^~ /wordpress {
root /var/www/example.com;
index index.php index.html index.htm;
try_files $uri $uri/ @wp;
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass 127.0.0.1:9000;
}
}or if you really do need path info (urls look like /wordpress/index.php/foo/bar):location ^~ /wordpress {
root /var/www/example.com;
index index.php index.html index.htm;
try_files $uri $uri/ /wordpress/index.php;
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 PATH_TRANSLATED $document_root$fastcgi_path_info;
fastcgi_pass 127.0.0.1:9000;
}
}EDIT: Updated first server{} to strip initial /wordpress from uri and pass remainder as q paramEDIT2: Named locations are only valid at server level | I've tried so many different things. The point I'm at right now is this:location ^~ /wordpress {
alias /var/www/example.com/wordpress;
index index.php index.html index.htm;
try_files $uri $uri/ /wordpress/index.php;
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_split_path_info ^(/wordpress)(/.*)$;
fastcgi_param SCRIPT_FILENAME /var/www/example.com/wordpress/index.php;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}Right now, all resources as far as I can tell (images, etc) are loading correctly. Andhttp://www.example.com/wordpressloads wordpress, but a page that says "page not found". (Wordpress is in use for this though). If I try any post urls I get the same result, "page not found". So I know the problem is that wordpress isn't obtaining the data about the path or something. Another potential problem is that if I runexample.com/wp-admin.phpthen it will still runindex.php.What data needs to be passed? What may be going wrong here? | Nginx - wordpress in a subdirectory, what data should be passed? |
You need to rename your bucket to match the custom domain name (e.g.imagens.mydomain.com.br) and set up that domain as a CNAME to.s3.amazonaws.com.(in your caseimagens.mydomain.com.br.s3.amazonaws.com.The full instructions are available here:http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html | Good morning,I am using amazon s3 bucket as the image server.
And I want to use a subdomain of my site, how to address this bucket.
eg: a picture is now in:https://s3-sa-east-1.amazonaws.com/nomeBucket/pasta/imag.png, and I access it through this same link.Would that it were so: imagens.mydomain.com.br / folder / imag.png
Is there any way I can do this? appoint a subdomain address to a bucket?
I've tried the amazon route 53, as CNAME. I tried this:https://s3-sa-east-1.amazonaws.com/nomeBucket/I took the test yesterday, but apparently it did not work.
Someone already did something similar, and / or know how to help me?Note: I'm using nginx. also need to configure it for subdomain?Thank you | how appoint a subdomain for a s3 bucket? |
You can get around this by installingdnsmasqand setting your resolver to127.0.0.1. Basically this uses your local DNS as a resolver, but it only resolves what it knows about (among those things is your/etc/hosts) and forwards the rest to your default DNS. | Can/etc/hostsbe used instead ofresolverwhen usingproxy_pass?I need to perform a proxy_pass to the same nginx machine. Is there a way to resolve the domains using the machine's /etc/hosts file instead of specifying a DNS server thru the "resolver" property?This will save me the additional hops needed to reach the same server. I have tried setting up the internal IP mapped to the DNS in /etc/hosts file but nginx is still reading from the DNS server set in theresolverproperty. Or is there a way to make the HTTPProxy module to consider the /etc/hosts file settings?Thanks for any advice you could share..This is the same question I posted in the nginx forum:http://forum.nginx.org/read.php?11,218997 | When using proxy_pass, can /etc/hosts be used to resolve domain names instead of "resolver"? |
The SSL redirect won't work if your SSL certificate doesn't support the non-www domain.
The config is correct but can be reduced to just 1 redirect serverAlso don't forget to reload Nginxsudo service nginx reloadserver {
listen 80;
listen 443 ssl;
server_name example.com;
# add ssl settings
return 301 https://www.example.com$request_uri;
} | I'm setting up an Nginx server with an SSL.The domain with the SSL iswww.mydomain.exampleI want to redirect all requests from:http://mydomain.example,http://www.mydomain.example, &https://mydomain.exampletohttps://www.mydomain.exampleI have the following server blocks setup currently:server{
listen 443 ssl;
root /www/mydomain.example/;
ssl_certificate /ssl/domain.crt;
ssl_certificate /ssl/domain.key;
.
.
.
}
server{
listen 80;
server_name mydomain.example;
return 301 https://www.mydomain.example$request_uri;
}
server{
listen 80;
server_name www.mydomain.example;
return 301 https://www.mydomain.example$request_uri;
}
server{
listen ssl 443;
server_name mydomain.example;
return 301 https://www.mydomain.example$request_uri;
}This currently does not work, but I don't understand why not. I can get a combination of either HTTP -> HTTPS working or no-www to -> www working, but mixing them as above does not work. | Nginx Redirect HTTP to HTTPS and non-www to ww |
This isa long standing bug in nginx. But you can work around by using therootdirective again. Kind of a hack, but at least it works.server {
index index.php;
root /home/alex/www/test2;
server_name local.test.ru;
location /blog {
root /home/alex/www/test1;
try_files $uri $uri/ /blog$is_args$args;
}
} | I'm trying to serve request to /blog subdirectory of a site with the php code, located in a folder outside document root directory. Here's my host config:server {
server_name local.test.ru;
root /home/alex/www/test2;
location /blog {
alias /home/alex/www/test1;
try_files $uri $uri/ /index.php$is_args$args;
location ~ \.php$ {
fastcgi_split_path_info ^(/blog)(/.*)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
}
}
}And I get for requests likewget -O -http://local.test.ru/blog/nonExistingjust a code of index.php file from /home/alex/www/test2/ folder.However, this config:server {
server_name local.test.ru;
root /home/alex/www/test2;
location /blog {
alias /home/alex/www/test1;
try_files $uri $uri/ /blog$is_args$args;
index index.php;
location ~ \.php$ {
fastcgi_split_path_info ^(/blog)(/.*)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
}
}
}gives me index.html file from /home/alex/www/test2/.
Please give me a clue - why? And how can I force NGINX to process /home/alex/www/test1/index.php instead? | NGINX try_files + alias directives |
To build on mark's answer, Debian/Ubuntu distros default configuration file has aninclude /etc/nginx/sites-enabled/*;directive with site configuration file stored in/etc/nginx/sites-available/, a default site is usually included in that dir.For examples beyond the default config, follownginx beginner's guideor seewiki.nginx.orgfor more details.After creating a new configuration insites-available, create a symbolic link with this command, assuming that your conf file is named "myapp" and nginx is at /etc/nginx (could also be at /usr/local/etc/nginx):ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myappBy the way, you could always create your conf file directly in sites-enabled but the recommended way above allows you to "enable and disable" sites on the server very quickly without actually moving/deleting your conf files.P.S:Don't trust the tutorials: check your configuration!P.P.S: You can use the commandnginx -tto test your sites conf andnginx -s reloadto reload the conf. | I'm just starting to explore nginx on my ubuntu 10.04. I installed nginx and I'm able to get the "Welcome to Nginx" page on localhost. However I'm not able to add a newserver_name.Even when I make the changes insite-available/default. I also tried reloading/restarting nginx, but nothing works. | How do I add new site/server_name in nginx? |
I had the same question, and @vladiastudillo answer was the missing piece I needed.First add the nginx stable repo:sudo add-apt-repository ppa:nginx/stableThen run apt update:sudo apt-get updateAnd get the nginx geoip module:sudo apt-get install nginx-module-geoipThis will download and load the module to/usr/lib/nginx/modulesTo load the nginx module,opennginx.conf:sudo nano /etc/nginx/nginx.confadd add below in the main context:load_module "modules/ngx_http_geoip_module.so";The module will be loaded, when you reload the configuration or restart nginx.To dynamically “unload” a module, comment out or remove itsload_moduledirective and reload the nginx configuration. | IntroductionFrom NGINX version 1.9.11 and upwarts, a new feature is introduced: dynamic modules.With dynamic modules, you can optionally load separate shared object files at runtime as modules – both third-party modules and some native NGINX modules. (source)My setup and the problemI have NGINX installed from the mainline (currently 1.9.14) so it is capable to use dynamic modules. It has also the module I want dynamicly enabled:nginx -V
nginx version: nginx/1.9.14
built by gcc 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.1)
built with OpenSSL 1.0.1f 6 Jan 2014
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules ... --with-http_geoip_module=dynamic ...Note the--with-http_geoip_module=dynamicwhich loads the module I need (dynamically).
Unfortunately, the documentation is lacking (some details) and I am unable to set this up.I have an existing NGINX installation (not from source). But so far as I can understand I just need to build the module, place the generated module file in the right NGINX folder and enable it in the config file.What I tried so farI tested this on a different machine (with the same configuration, but not a production machine), but I don't see thengx_http_geoip_module.sofile.
The commands I used:wget http://nginx.org/download/nginx-1.9.14.tar.gz
tar -xzf nginx-1.9.14.tar.gz
cd nginx-1.9.14/
./configure --with-http_geoip_module=dynamicThe questionsIs it a problem that I try to build the module on a system that has
NGINX installednotfrom source?Why is there no .so file generated by my commands? | How to enable dynamic module with an existing NGINX installation |
It may be the case that when you upload things, you use chunked encoding.
There is uWSGI option--chunked-input-timeout,
that by default is 4 seconds (itdefaultsto value of--socket-timeout, which is 4 seconds).Though problem theoretically may lie somewhere else, I suggest you to try
aforementioned options. Plus, annoying exceptions are the reason why I haveignore-sigpipe=true
ignore-write-errors=true
disable-write-exception=truein my uWSGI config (note that I provide 3 options, not 2):ignore-sigpipemakes uWSGI not show SIGPIPE errors;ignore-write-errorsmakes it not show errors with
e.g.uwsgi_response_writev_headers_and_body_do;disable-write-exceptionpreventsOSErrorgeneration on writes. | My application uses nginx, with uWSGI on the server side. When I do a large request (with a response time > 4s), the following appears:SIGPIPE: writing to a closed pipe/socket/fd (probably the client
disconnected) on request _URL_ (ip XX.XX.XX.XX) !!!
uwsgi_response_writev_headers_and_body_do(): Broken pipe
[core/writer.c line 287] during GET _URL_ (XX.XX.XX.XX)
OSError: write errorIt seems that uWSGI tries to write in a stream but this stream has already been closed.
When I check nginx log (error.log):upstream prematurely closed connection while reading response
header from upstream ...Of course, my client (REST client or browser) receives a 502 error.I always get this error after ~4s.However, I don't know how to prevent this issue.
I tried to set some parameters in my nginx config file:location my_api_url {
[...]
uwsgi_buffer_size 32k;
uwsgi_buffers 8 32k;
uwsgi_busy_buffers_size 32k;
uwsgi_read_timeout 300;
uwsgi_send_timeout 300;
uwsgi_connect_timeout 60;
}But the issue is still here.
I also tried to set these parameters in the uWSGI configuration file (wsgi.ini):buffer-size=8192
ignore-sigpipe=true
ignore-write-errors=trueBefore to try to optimize the response time, I hope this issue has a solution. I don't find one that's working in another post. I work with a large amount of data, so my response time, for some case, will be between 4-10s.Hope you can help me :)Thanks a lot in advance. | uWSGI raises OSError: write error during large request |
The inheritance of config directives in Nginx is such that directives can only be inherited from contexts higher up the configuration tree and never from contexts on the same level or lower.So, a location block cannot inherit from another location block but a nested location blockcaninherit from the parent location block.I stressedcanbecause there are a number of different types of directives and the inheritance behaviour is a bit different for each.There are Standard Type Directives which only have one value or set
of values attached. These will simply be inherited by contexts lower
down the config tree or replaced within that lower context by new
values. An example is "index".Array Type Directives which pass multiple separate values in an
array. These will simply be inherited by contexts lower down the
config tree or replaced within that lower context by new values.
Note that you cannot add to the array. Changing part is replacing it
all. An example is "proxy_param". So if you define proxy_param A and
proxy_param B at the server level for instance, and then try to
define proxy_param C in a location context, "A" and "B" would be
wiped out (set to default values). as defining "C" has meant
replacing the array.Command Type Directives such as "try_files" are generally not
inherited at all.So specifically to your question, directives defined in one location block context cannot be inherited by another as in your second example.Standard and Array type directives defined in the parent location block will be inherited by the nested location block. Command type directives defined in the parent will not be inherited in general. | are the following two nginx server blocks semantically the same, or is there any difference? Does the JSON-specific configuration in the first example inherit the settings of the "/" location? Does it in the second example?server {
location / {
# ...
location ~* \.json$ {
# json-specific settings
}
}
}
server {
location / {
# ...
}
location ~* \.json$ {
# json-specific settings
}
} | Directive Inheritance in Nested Location Blocks |
Nginx routing is based on the location directive which matches on the Request URI. The solution is to temporarily modify this in order to forward the request to different endpoints.server {
listen 80 default;
server_name test.local;
if ($request_body ~* ^(.*)\.test) {
rewrite ^(.*)$ /istest/$1;
}
location / {
root /srv/http;
}
location /istest/ {
rewrite ^/istest/(.*)$ $1 break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://www.google.de;
}
}Theifcondition can only safely be used in Nginx with therewrite modulewhich it is part of. In this example. Therewriteprefixes the Request URI withistest.Thelocationblocks give precedence to the closest match. Anything matching/istest/will go to the second block which uses anotherrewriteto remove/istest/from the Request URI before forwarding to the upstream proxy. | i am trying to configure nginx to proxy pass the request to another server,
only if the $request_body variable matches on a specific regular expression.My problem now is, that I don't how to configure this behaviour exactly.I am currently down to this one:server {
listen 80 default;
server_name test.local;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
if ($request_body ~* ^(.*)\.test) {
proxy_pass http://www.google.de;
}
root /srv/http;
}
}but the problem here is, that root has always the upperhand.
the proxy won't be passed either way.any idea on how I could accomplish this?thanks in advance | nginx conditional proxy pass |
After investigating this some more I found out that I hadn't set the charset in my main Nginx config file:http {
charset utf-8;
}By adding the above, the problem disappeared and I think that this is the correct way of handling this issue. | When uploading files with non-ASCII characters I get UnicodeEncodeError:Exception Type: UnicodeEncodeError at /admin/studio/newsitem/add/
Exception Value: 'ascii' codec can't encode character u'\xf8' in position 78: ordinal not in range(128)Seefull stack trace.I run Django 1.2 with MySQL and nginx and FastCGI.This is a problem that is fixed according to theDjango Trac database, but I still have the problem. Any suggestions on how to fix are welcome.EDIT: This is my image field:image = models.ImageField(_('image'), upload_to='uploads/images', max_length=100) | UnicodeEncodeError: 'ascii' codec can't encode character |
This is from the nginxdocumentation.gzip_vary
syntax: gzip_vary on|off
default: gzip_vary off
context: http, server, locationEnables response header of"Vary: Accept-Encoding". Note that this
header causes IE 4-6 not to cache the content due to a bug (see2).There if you just addgzip_vary on;it should do it's job.Also make sure you have any one of the directives gzip, gzip_static, or gunzip are active. | I have an nginx server and can't seem to find any information on how to send Vary: Accept-Encoding headers for CSS and JS files. Does anyone have info about this?Thanks! | Set Vary: Accept-Encoding Header (nginx) |
The three services are being proxied by the same server (as far asnginxis concerned) so must be structured as threelocationblocks within oneserverblock. Seethis documentfor details.If you are just passing the original URI unmodified, you do not need to specify a URI on theproxy_passstatement.server {
{
listen 443;
server_name localhost;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
location /api/orders {
proxy_pass https://localhost:500;
}
location /api/customers {
proxy_pass https://localhost:400;
}
location = /api/customers {
proxy_pass https://localhost:300;
}
}If theproxy_set_headerstatements are identical, they can be specified once in the parent block.The type oflocationstatement required is dependent on the range of URIs processed by thelocalhost:300/api/customers/service. If it is one URI, the=syntax will work. If it is any URI that does not match/api/customers/:id/billing, then you will need to use a regular expression location block. Seethis documentfor details.I am not sure that this will work unless you terminate SSL here. That is configure thereverse proxy as a secure server. | I have the following API(s):localhost:300/api/customers/localhost:400/api/customers/:id/billinglocalhost:500/api/ordersI'd like to use NGINX to have them all run under the following location:localhost:443/api/This seems very difficult because of customers spanning two servers.Here's my failed attempt starting with ordersserver {
listen 443;
server_name localhost;
location /api/orders {
proxy_pass https://localhost:500/api/orders;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
server {
listen 443;
server_name localhost;
location /api/customers/$id/billing {
proxy_pass https://localhost:400/api/customers/$id/billing;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
server {
listen 443;
server_name localhost;
location /api/customers {
proxy_pass https://localhost:300/api/customers;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
}Anything jump out as far as a fix? Thanks! | NGINX - Reverse proxy multiple API on different ports |
Here's a tool I use:http://www.anilcetin.com/convert-apache-htaccess-to-nginx/It is not 100% accurate but it's pretty good baseAlso, here's a link about converting the rules:http://nginx.org/en/docs/http/converting_rewrite_rules.htmlThis one can help a little:http://wiki.nginx.org/HttpRewriteModule#rewriteEDIT:The file name should benginx.conf | I'm migrating a website from a server that has Apache web-server to another server that is running Nginx web-server, and I wanted to convert the .htaccess files, the problem is not just the syntax but also the file name, is it also".htaccess"or what? | Change Apache .htaccess file to be used with Nginx |
To citethe docson theserver_tokensdirective:Enables or disables emitting nginx version in error messages and in the “Server” response header field.According to the docs, it thus doesn't prevent the generation of theServerheader but only prevents the addition of the exact version. If you want to completely remove the servers header, you could usethe ngx_headers_more module. | nginx.conf:server_tokens off;Why could this get ignored, the header is still sent:Server: nginxNo, other included config files do not containserver_tokensconfiguration.Yes, I did restart all services. | nginx "server_tokens off" does not remove the server header |
Nginxis a really light and easy to use solution and along withgunicornit allows us to run any wsgi application and scale it easily.
Nginx is better at handling requests since it does not spawn a new process for every request unlike Apache.I have written an answer on how to deploy django with nginx for a related question:Deploying Django project with Gunicorn and nginx | I want to deploy a django site (it is the open source edx code on github).I am faced with choosing between usingApache with mod_wsginginx with gunicornI have used Apache with mod_wsgi and it's cool enough, but i have no experience with the second option.Which of these would be a better option in terms of speed and also to some extent, ease of use?NB: I would need to run two different django sites on say, port 80 and 81 and access them from two different subdomains. | Apache + mod_wsgi vs nginx + gunicorn |
You can create an additional filessl.confand put here ssl configs:ssl_certificate /etc/nginx/certs/atvcap_cabundle.crt;
ssl_certificate_key /etc/nginx/certs/atvcap.key;Then include from the main config:server_name atvcap.server.com;
include /somepath/ssl.conf*;Make sure to include * symbol - this will not break when the file does not exist at development mode. | I have an issue wherein I am building an nginx reverse proxy for directing to multiple microservices at different url paths.The system is entirely docker based and as a result the same environment is used for development and production. This has caused an issue for me when installing SSL as the SSL certs will only be available in production so when I configure NGINX with SSL the development environment no longer works as the ssl certs are not present.Here is the relevant part of my conf file -server {
listen 80;
listen 443 default_server ssl;
server_name atvcap.server.com;
ssl_certificate /etc/nginx/certs/atvcap_cabundle.crt;
ssl_certificate_key /etc/nginx/certs/atvcap.key;
...
}But this throws the following when running my application in development mode -nginx: [emerg] BIO_new_file("/etc/nginx/certs/atvcap_cabundle.crt") failed (SSL: error:02001002:system library:fopen:No such file or directory:fopen('/etc/nginx/certs/atvcap_cabundle.crt','r') error:2006D080:BIO routines:BIO_new_file:no such file)Is it possible to only turn on SSL if the "/etc/nginx/certs/atvcap_cabundle.crt" is available?I had tried something like the following -if (-f /etc/nginx/certs/atvcap_cabundle.crt) {
ssl_certificate /etc/nginx/certs/atvcap_cabundle.crt;
ssl_certificate_key /etc/nginx/certs/atvcap.key;
}But that threw the following error -nginx: [emerg] "ssl_certificate" directive is not allowed here in
/etc/nginx/conf.d/default.conf:7Any one have any ideas on how to achieve something like this?Thanks | Nginx - Only enable SSL if SSL Certificates Exist |
I had the same problem, that is, after upgrading from Mavericks to Yosemite I got the following error:nginx: [emerg] mkdir() "/usr/local/var/run/nginx/client_body_temp" failed (2: No such file or directory)All I needed to do to solve this issue was to create the folder:mkdir -p /usr/local/var/run/nginx/client_body_temp | Nginx was working fine on Mavericks, and now after I upgraded to Yosemite its displayingnginx command not found, I tried to install nginx withbrew install nginxand it displays an errorError: You must brew link pcre before nginx can be installedAndbrew link pcredisplaysLinking /usr/local/Cellar/pcre/8.35... Error: No such file or directory - /usr/local/Cellar/pcre/8.34/share/doc/pcreIts trying to link 8.34. I reinstalled still its same, How do i solve it? | Nginx broken after upgrade to osx yosemite |
add_headerhas to be placed under eitherhttp,server,locationorif in locationblock.You are placing in underif in server. Move them under thelocationblock.server {
listen 8080;
location / {
root /var/www/vhosts/mysite;
if ($http_origin ~* (https?://[^/]*\.domain\.com(:[0-9]+)?)$) {
set $cors "true";
}
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
if ($request_method = 'GET') {
set $cors "${cors}get";
}
if ($request_method = 'POST') {
set $cors "${cors}post";
}
if ($cors = "trueget") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
}
if ($cors = "truepost") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
}
if ($cors = "trueoptions") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 204;
}
}
}Source:http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header | I am trying add CORS directive to my nginx file for as simple static HTML site. (taken from herehttp://enable-cors.org/server_nginx.html)Would there be a reason why it would complain about the first add_header directive saying 'add_header" directive is not allowed here'My config file sampleserver {
if ($http_origin ~* (https?://[^/]*\.domain\.com(:[0-9]+)?)$) {
set $cors "true";
}
if ($request_method = 'OPTIONS') {
set $cors "${cors}options";
}
if ($request_method = 'GET') {
set $cors "${cors}get";
}
if ($request_method = 'POST') {
set $cors "${cors}post";
}
if ($cors = "trueget") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
}
if ($cors = "truepost") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
}
if ($cors = "trueoptions") {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 204;
}
listen 8080;
location / {
root /var/www/vhosts/mysite;
}
} | Nginx Config for Cors - add_header directive is not allowed |
Seeing the exact same error on Nginx 1.9.0 and it looks like it was caused by the HTTPS endpoint using SNI.Adding this to the proxy location fixed it:proxy_ssl_server_name on;https://en.wikipedia.org/wiki/Server_Name_Indicationhttp://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_server_name | So i am using following settings to create one reverse proxy for site as below.server {
listen 80;
server_name mysite.com;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
root /home/ubuntu/p3;
location / {
proxy_pass https://mysiter.com/;
proxy_redirect https://mysiter.com/ $host;
proxy_set_header Accept-Encoding "";
}
}But getting BAD GATE WAY 502 error and below is the log.2016/08/13 09:42:28 [error] 26809#0: *60 SSL_do_handshake() failed (SSL: error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error) while SSL handshaking to upstream, client: 103.255.5.68, server: mysite.com, request: "GET / HTTP/1.1", upstream: "https://105.27.188.213:443/", host: "mysite.com"
2016/08/13 09:42:28 [error] 26809#0: *60 SSL_do_handshake() failed (SSL: error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error) while SSL handshaking to upstream, client: 103.255.5.68, server: mysite.com, request: "GET / HTTP/1.1", upstream: "https://105.27.188.213:443/", host: "mysite.com"Any help will be greatly appreciated. | Nginx reverse proxy error:14077438:SSL SSL_do_handshake() failed |
Removessl on;directive.sslflag inlistendirective is exactly what you need.Seehttp://nginx.org/en/docs/http/configuring_https_servers.html#single_http_https_server | I have a config file with a virtual server setup, this is running on port 443 for ssl. I would also like this same virtual server to handle non ssl traffic on port 80.I was hoping to do the following but it doesn't seem to work.server {
listen 443 ssl;
listen 80;
server_name example.com;
...
}It looks like the ssl options below these settings are causing problems for the non ssl traffic. | How can a single nginx virtual server deal with both port 80 and 443? |
Apparently alias and try_filesdon't work together. However, I don't think you need to use alias.location /mr {
default_type "text/html";
try_files /fullpath/$uri /fullpath/$uri.html /fullpath/$uri/index.html /fullpath/index.html;
}Which would try:Exact file.File with .html added.Index in the path.Default index.I think the root directive does work with try files but am unable to test.server{
location /mr {
root /home/mysite/fullpath;
default_type "text/html";
try_files $uri $uri.html $uri/index.html index.html;
}
} | I'm having a lot of trouble setting up this alias inside nginx to display my website correctly.The website I'm concerned with should be accessible frommywebsite.com/mrand is different from the site located atmywebsite.com/. The website is located at/fullpath(shortened for simplicity) The site needs to serve three kinds of content:The index file located in/fullpath/index.html.Other html files (without showing the.htmlextension in the browser).Static assets (js/css/img) located in/fullpathand subdirectories.I've tried changing around the order of matches in thetry_filesand found situations where they all worked, just not at the same time:location /mr {
default_type "text/html";
alias /fullpath;
# with this one 1 and 3 work
# try_files $uri/index.html $uri.html $uri;
# with this one 2 and 3 work
# try_files $uri $uri.html $uri/index.html;
# with this one 1 and 2 work
try_files $uri.html $uri/index.html $uri;
}When one doesn't work it 404's. Does anybody know how I can serve all kinds of files correctly? | how to serve html files in nginx without showing the extension in this alias setup |
The problem is that clients abort the connection and then Nginx closes the connection without telling uwsgi to abort. Then when uwsgi comes back with the result the socket is already closed. Nginx writes a 499 error in the log and uwsgi throws a IOError.The non optimal solution is to tell Nginx not to close the socket and wait for uwsgi to come back with a response.Put uwsgi_ignore_client_abort in your nginx.config.location @app {
include uwsgi_params;
uwsgi_pass unix:///tmp/uwsgi.sock;
# when a client closes the connection then keep the channel to uwsgi open. Otherwise uwsgi throws an IOError
uwsgi_ignore_client_abort on;
}It is not clear if it is possible to tell Nginx to close the uwsgi connection. There is another SO questin about this issues: (Propagate http abort/close from nginx to uwsgi / Django) | I have a problem with my nginx+uwsgi configuration for my django app, I keep getting this errors in the uwsgi error log:Wed Jan 13 15:26:04 2016 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 296] during POST /company/get_unpaid_invoices_chart/ (86.34.48.7)
IOError: write errorWed Jan 13 15:26:20 2016 - uwsgi_response_write_headers_do(): Broken
pipe [core/writer.c line 238] during GET
/gestiune/print_pdf/nir/136194/ (89.122.255.186) IOError: write errorI am not getting them for all the requests but I do get a couple of them each minute.
I searched for it and I understand that this happens because nginx closes the connection to uwsgi by the time uwsgi wants to write the response.
This looks strange because in my nginx configuration I have this:include uwsgi_params;uwsgi_pass unix:/home/project/django/sbo_cloud/site.sock;uwsgi_read_timeout 600;uwsgi_send_timeout 600;uwsgi_connect_timeout 60;I am certain that none of the requests for which the error appears has exceeds the 600 seconds timeout.
Any idea why this would happen?Thanks | uwsgi IOError: write error |
# abc.example.com
server {
listen 80;
server_name abc.example.com;
location / {
proxy_pass http://127.0.0.1/abc$request_uri;
proxy_set_header Host example.com;
}
} | The idea is to take incoming requests tohttp://abc.example.com/...and rewrite them tohttp://example.com/abc/...That's easy enough to do with a 301/302 redirect:# rewrite via 301 Moved Permanently
server {
listen 80;
server_name abc.example.com;
rewrite ^ $scheme://example.com/abc$request_uri permanent;
}The trick is to do this URL changetransparentlyto the client whenabc.example.comandexample.compoint at the same Nginx instance.Put differently, can Nginx serve the contents fromexample.com/abc/...whenabc.example.com/...is requested andwithout another client round trip?Starting Point ConfigNginx config that accomplishes the task with a 301:# abc.example.com
server {
listen 80;
server_name abc.example.com;
rewrite ^ $scheme://example.com/abc$request_uri permanent;
}
# example.com
server {
listen 80;
server_name example.com;
location / {
# ...
}
} | Nginx convert subdomain to path component without redirect |
Technically just adding the URI should work, because it'sdocumented hereand it says that it should work, solocation @test{
proxy_pass http://localhost:5000/1/; # with a trailing slash
}Should have worked fine, but since you said it didn't I suggested the other way around, the trick is that instead of passing/my/uritolocalhost:5000/1, we pass/1/my/uritolocalhost:5000,That's what my rewrite didrewrite ^ /1$1Meaning rewrite the whole URL, prepend it with/1then add the remaining, the whole block becomeslocation @test{
rewrite ^ /1$1;
proxy_pass http://localhost:5000;
}Note:@Fleshgrinderprovided an answerexplaining why the first method didn't work. | I have alocationblock aslocation @test{
proxy_pass http://localhost:5000/1;
}but nginx complains that"proxy_pass cannot have URI part in location given by regular expression..."Does anyone know what might be wrong?I'm trying to query localhost:5000/1 when an upload is complete:location /upload_attachment {
upload_pass @test;
upload_store /tmp;
...
} | nginx 'proxy_pass' cannot have URI part in location? |
I just changedgzip_http_version 1.1;to begzip_http_version 1.0;and then it worked | I am trying to enable gzip compression for components of my website. I use Ubuntu 11.04 server and Nginx 1.2.In my Nginx configuration of the website, I have this:gzip on;
#gzip_min_length 1000;
gzip_http_version 1.1;
gzip_vary on;
gzip_comp_level 6;
gzip_proxied any;
gzip_types text/plain text/html text/css application/json application/javascript application/x-javascript text/javascript text/xml application/xml application/rss+xml application/atom+xml application/rdf+xml;
#it was gzip_buffers 16 8k;
gzip_buffers 128 4k; #my pagesize is 4
gzip_disable "MSIE [1-6]\.(?!.*SV1)";Yslow and Google speed measures advise me to use gzip to reduce transmission over the network.Now when I try tocurl -I my_js_file, I get:curl -I http://www.albawaba.com/sites/default/files/js/js_367664096ca6baf65052749f685cac7b.js
HTTP/1.1 200 OK
Server: nginx/1.2.0
Date: Sun, 14 Apr 2013 13:15:43 GMT
Content-Type: application/x-javascript
Content-Length: 208463
Connection: keep-alive
Last-Modified: Sun, 14 Apr 2013 10:58:06 GMT
Vary: Accept-Encoding
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Pragma: public
Cache-Control: public
Accept-Ranges: bytesAny idea of what I have done wrong or what shall I do to get compressed content? | Enable gzip compression with Nginx |
You should usealiasinstead ofroot.rootappends the trailing URL parts to your local path (e.g.http://test.ndd/trailing/part, it will add /trailing/part to your local path). Instead of that,aliasdoes exactly what you want: whenhttp://test.ndd/static/is requested, /static is mapped to your alias exactly, without appending static again.For example:location /static {
alias /var/www/django/ecerp/erp/static/;
}And if file/var/www/django/ecerp/erp/static/foo.htmlexists then going to/static/foo.htmlwill return its contents. | I'm now deploying an django app with nginx and gunicorn on ubuntu 12.And I configure the nginx virtual host file as below:server {
listen 80;
server_name mydomain.com;
access_log /var/log/nginx/gunicorn.log;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /static/ {
root /var/www/django/ecerp/erp/static/;
}
}I can request the django well, but when request a static file, it response with 404 status.I'm sure the root path of static file is correct.Can anyone help? | Fetching static files failed with 404 in nginx |
Nginx hasssl_password_fileparameter.Specifies afilewith passphrases for secret keys where each passphrase is specified on a separate line. Passphrases are tried in turn when loading the key.Example:http {
ssl_password_file /etc/keys/global.pass;
...
server {
server_name www1.example.com;
ssl_certificate_key /etc/keys/first.key;
}
server {
server_name www2.example.com;
# named pipe can also be used instead of a file
ssl_password_file /etc/keys/fifo;
ssl_certificate_key /etc/keys/second.key;
}
}What you could do is keep thatssl_password_filein ansible-vault, copy it over, restart nginx and then if successful delete it.I have no first-hand experience if it'll actually work or what other side-effects this might have(for example manualservice nginx restartwill probably fail), but it seems like a logical approach to me. | I configured nginx installation and configuration (together with setup SSL certificates forhttpssite) viaansible. SSL certificates are under passphrases.I want to write ansilbe task which is restarting nginx. The problem is the following.Normally, nginx with https site inside asks forPEM pass phraseduring restart. Ansible doesn't ask for that passphrase during execution of playbook.There issolutionwith storing decrypted cert and key in some private directory. But I don't really want to leave my cert and key somewhere unencrypted.How to pass password to nginx (or to openssl) during restart viaansible? Perfect scenario is following:Ansible is asking for SSL password (viavars_promt). Another option is to use ansible vault.Ansible is restarting nginx, and when nginx is asking forPEM pass phrase, ansible is passing password to nginx.Is it possible? | Pass cert password to Nginx with https site during restart |
You better usehttp://example.com/?mobile=1(argument with value). In this case checking is simple:if ($arg_mobile) {
return 302 http://m.example.com/;
}Checking for argument existance is usually done with regexp likeif ($args ~ mobile)but it's error-prone, because it will matchmobileanywhere, e.g.http://example.com/?tag=automobile. | I want to check if a parameter is present in a url in nginx and then rewrite.How can i do that?For e.g if url ishttp://website.com/?mobilethen redirect user tohttp://m.website.com | Making nginx check parameter in url |
You can't use nginx for this currently[it's not true anymore], but I would suggest looking at HAProxy. I have used it for exactly this purpose.The trick is to set long timeouts so that the socket connections are not closed. Something like:timeout client 86400000 # In the frontend
timeout server 86400000 # In the backendIf you want to serve say a rails and cramp application on the same port you can use ACL rules to detect a websocket connection and use a different backend. So your haproxy frontend config would look something likefrontend all 0.0.0.0:80
timeout client 86400000
default_backend rails_backend
acl websocket hdr(Upgrade) -i WebSocket
use_backend cramp_backend if websocketFor completeness the backend would look likebackend cramp_backend
timeout server 86400000
server cramp1 localhost:8090 maxconn 200 check | We're working on a Ruby on Rails app that needs to take advantage of html5 websockets. At the moment, we have two separate "servers" so to speak: our main app running on nginx+passenger, and a separate server using Pratik Naik'sCrampframework (which is running onThin) to handle the websocket connections.Ideally, when it comes time for deployment, we'd have the rails app running on nginx+passenger, and the websocket server would be proxied behind nginx, so we wouldn't need to have the websocket server running on a different port.Problem is, in this setup it seems that nginx is closing the connections to Thin too early. The connection is successfully established to the Thin server, then immediately closed with a 200 response code. Our guess is that nginx doesn't realize that the client is trying to establish a long-running connection for websocket traffic.Admittedly, I'm not all that savvy with nginx config, so, is it even possible to configure nginx to act as a reverse proxy for a websocket server? Or do I have to wait for nginx to offer support for the new websocket handshake stuff? Assuming that having both the app server and the websocket server listening on port 80 is a requirement, might that mean I have to have Thin running on a separate server without nginx in front for now?Thanks in advance for any advice or suggestions. :)-John | Can nginx be used as a reverse proxy for a backend websocket server? |
Your code appears to be using a forward proxy (often just "proxy"), not reverse proxy and they operate quite differently. Reverse proxy is for server end and something client doesn't really see or think about. It's to retrieve content from the backend servers and hand to the client. Forward proxy is something the client sets up in order to connect to rest of the internet. In turn, the server may potentially know nothing about your forward proxy.Nginx is originally designed to be a reverse proxy, and not a forward proxy. But it can still be used as a forward one. That's why you probably couldn't find much configuration for it.This is more a theory answer as I've never done this myself, but a configuration like following should work.server {
listen 8888;
location / {
resolver 8.8.8.8; # may or may not be necessary.
proxy_pass http://$http_host$uri$is_args$args;
}
}This is just the important bits, you'll need to configure the rest.The idea is that the proxy_pass will pass to a variable host rather than a predefined one. So if you requesthttp://example.com/foo?bar, your http header will include host ofexample.com. This will make your proxy_pass retrieve data fromhttp://example.com/foo?bar.The document that you linked is using it as a reverse proxy. It would be equivalent toproxy_pass http://localhost:80; | I am trying to configure NGINX as a forward proxy to replace Fiddler which we are using as a forward proxy. The feature of Fiddler that we use allows us to proxy ALL incoming request to a 8888 port. How do I do that with NGINX?In all examples of NGINX as a reverse proxy I seeproxy_passalways defined to a specific upstream/proxied server. How can I configure it so it goes to the requested server, regardless of the server in the same way I am using Fiddler as a forward proxy.Example:In my code:WebProxy proxyObject = new WebProxy("http://mynginxproxyserver:8888/",true);
WebRequest req = WebRequest.Create("http://www.contoso.com");
req.Proxy = proxyObject;In mynginxproxyserver/nginx.conf I do not want to delegate the proxying to another server (e.g. proxy_pass set tohttp://someotherproxyserver). Instead I want it to just be a proxy server, and redirect requests from my client (see above) to the request host. That's what Fiddler does when you enable it as a proxy:http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/UseFiddlerAsReverseProxy | How to use NGINX as forward proxy for any requested location? |
Nginx is a web server. You need to use an application server for your task, such asuWSGIfor example. It can talk with nginx using its native very effective binary interface called uwsgi. | I have problem setting up CGI scripts to be run on Nginx, so far I've foundhttp://wiki.nginx.org/SimpleCGIthis stuff but problem is that I can't make perl script run as service so that it will run in background and even in case of restart it will start running automaticallyDo you have any idea? I'm running Centos 5I've found some solutionsherebut I couldn't integrate code given there withthis Perl scriptI'm completely zero at Perl, please help me
Thanks | How to run CGI scripts on Nginx |
The issue is that yourDOCKER_HOSTis not set to localhost, you will need to use the IP address of your docker-machine, since you are using Docker Toolbox:docker-machine ip default# should return your IP address.SeeDocker Toolbox Docsfor more information. | I've installedDocker Toolboxin macOS and I'm following Docker's simple tutorial ondeploying Nginx.I've executeddocker runand confirmed that my container has been created:docker run --name mynginx1 -P -d nginx
docker ps
40001fc50719 nginx "nginx -g 'daemon off" 23 minutes ago Up 23 minutes 0.0.0.0:32770->80/tcp, 0.0.0.0:32769->443/tcp mynginx1however when Icurl http://localhost:32770, I get a connection refused error:curl: (7) Failed to connect to localhost port 32770: Connection refusedI'm struggling to see what I could have missed here. Is there an extra step I need to perform, in light of me being on macOS? | Connection refused on nginx docker container |
This isn't your problem.The best thing you can do in this situation is just to keep your server reasonably updated and secured.At best for you, the client side of a request was running seriously outdated software, and at worst your server is simply being scanned for vulnerabilities by compromised devices connected to the internet.Personally I lean in the direction of this being scanning, as I myself see these errors on a private development server, to which only I should ever have a legitimate reason to connect to, yet I see a ton of IP addresses mentioned by the error from around the world.Similar question and answer has already been provided here:https://serverfault.com/questions/905011/nginx-ssl-do-handshake-failed-ssl-error1417d18cssl/905019Stay safe. | I got this error in nginx error log:SSL_do_handshake() failed (SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share) while SSL handshakingI use Let's Encrypt currently. Any ideas to solve this problem? Thank you, guys. | Nginx SSL: error:141CF06C:SSL routines:tls_parse_ctos_key_share:bad key share |
If you set it, then you can only set it to DENY, SAMEORIGIN, or ALLOW-FROM (a specific origin).Allowing all domains is the default. Don't set theX-Frame-Optionsheader at all if you want that.Note that the successor toX-Frame-Options—CSP'sframe-ancestorsdirective— accepts alistof allowed origins so you can easily allowsomeorigins instead of none, one or all. | I am trying to use some site of mine as aniframefrom a different site of mine.My problem is- the other site is always consistently changes his IP address and does not have an domain name.So, I read that you can allo a specific domain by adding this lint to the/etc/nginx/nginx.conf:add_header X-Frame-Options "ALLOW-FROM https://subdomain.example.com/";My question is: It is possible to allow my site to be imported as an iframe from all IP addressed and domains? What should I write in order to achieve this?I am using Ubuntu 16.04 and nginx 1.10.0. | Change the X-Frame-Options to allow all domains |
Came across this error recently.SincePassenger 3.0.8there is now a setting that allows you to set the buffers and buffer size. So now you can dohttp {
...
passenger_buffers 8 16k;
passenger_buffer_size 32k;
}That resolved the issue for me. | I'm running nginx, Phusion Passenger and Rails.I am running up against the following error:upstream sent too big header while reading response header from upstream, client: 87.194.2.18, server: xyz.com, request: "POST /user_session HTTP/1.1", upstream: "passenger://unix:/tmp/passenger.3322/master/helper_server.sockIt is occuring on the callback from an authentication call to Facebook Connect.After googling, and trying to change nginx settings including proxy_buffer_size and large_client_header_buffers is having no effect.How can I debug this? | How to avoid nginx "upstream sent too big header" errors? |
Nginx doesn't parse the client request body unless it really needs to, so it usually does not fill the$request_bodyvariable.The exceptions are when:it sends the request to a proxy,or a fastcgi server.So you really need to either add theproxy_passorfastcgi_passdirectives to your block.The easiest way is to send it to Nginx itself as a proxied server, for example with this configuration:location = /c.gif {
access_log logs/uaa_access.log client;
# add the proper port or IP address if Nginx is not on 127.0.0.1:80
proxy_pass http://127.0.0.1/post_gif;
}
location = /post_gif {
# turn off logging here to avoid double logging
access_log off;
empty_gif;
}If you only expect to receive some key-pair values, it might be a good idea to limit the request body size:client_max_body_size 1k;
client_body_buffer_size 1k;
client_body_in_single_buffer on;I also received "405 Not Allowed" errors when testing usingempty_gif;and curl (it was ok from the browser), I switched it toreturn 200;to properly test with curl. | I'm trying to log POST body, and add$request_bodyto thelog_formatinhttpclause, but theaccess_logcommand just prints "-" as the body after I send POST request using:curl -d name=xxxx myip/my_locationMy log_format (inhttpclause):log_format client '$remote_addr - $remote_user $request_time $upstream_response_time '
'[$time_local] "$request" $status $body_bytes_sent $request_body "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';My location definition(in server clause):location = /c.gif {
empty_gif;
access_log logs/uaa_access.log client;
}How can I print the actual POST data from curl? | Really logging the POST request body (instead of "-") with nginx |
proxy_passandproxy_redirecthave totally different functions. Theproxy_redirectdirective is only involved with changing theLocationresponse header in a 3xx status message. Seethe NGINX proxy_redirect docsfor details.Yourrewritestatement does nothing other than prevent further modification of the URI. This line needs to be deleted otherwise it will inhibitproxy_passfrom mapping the URI. See below.Theproxy_passdirective can map the URI (e.g. from/v2/platform/general/footo/foo) by appending a URI value to theproxy_passvalue, which works in conjunction with thelocationvalue. Seethis documentfor details.For example:location /v2/platform/general/ {
...
proxy_pass http://another-IP:8080/;
}You may need to set the Host header only if your upstream server does not respond correctly to the valueanother-IP:8080.You may need to add one or moreproxy_redirectstatements if your upstream server generates 3xx status responses with an incorrect value for theLocationheader value. | Need help on Nginx proxy_pass.From outside Nginx URL will be hit like this:http://some-IP:8080/v2/platform/general/activity/plan?.....my downstream service looks like this:http://another-IP:8080/activity/plan?...I want to get rid of/v2/platform/generalfrom original public url and call my downstream service like above.In Nginx, how do I redirect public access URL to downstream service?I tried this:location /v2/platform/general/ {
rewrite ^/(.*) /$1 break;
proxy_redirect off;
proxy_pass http://another-IP:8080;
proxy_set_header Host $host;But it didn't work, any help appreciated. | NGINX proxy_pass or proxy_redirect |
DNS cannot redirect your www site to non-www. The only purpose of DNS is to point both www and non-www to your server's IP address usingA,AAAAorCNAMErecords (it makes little difference). Thenginxconfiguration is responsible for performing the redirect from www to non-www.Your second server block is intended to redirect from www to non-www, but currently only handleshttpconnections (on port 80).You can move the default server and use that to redirect everything to the intended domain name. For example:ssl_certificate /etc/nginx/ssl/cert_chain.crt;
ssl_certificate_key /etc/nginx/ssl/example_com.key;
server {
listen 80 default_server;
listen 443 ssl default_server;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
...
}Assuming that you have a common certificate for both the www and non-www domain names, you can move thessl_directives into the outer block and allow them to be inherited into both server blocks (as shown above).Seethis documentfor more. | I'm usingNamecheapDomains andVultrHosting.I'm trying to redirect DNS www to non-www.www.example.com to example.comI contacted Vultr and asked how to do this with their DNS Manager, they said they would not help as it is self-managed. So I contacted Namecheap, they said they would not help becuase they don't have access to Vultr's DNS Manager, would not tell me if the records I showed them are correct, and I would need to contact Vultr. So I am in an endless support loop.Vultr DNS ManagerI followedthis answeron how to set up a CNAME to redirect to non-www.Type | Name | Data | Seconds
--------------------------------------
A | | ipv4 address | 300
AAAA | | ipv6 address | 300
CNAME | . | example.com | 300
CNAME | www | example.com | 300After waiting all night for it to propgate, the www can still be visited and does not redirect.It does not allow me to make anotherArecord, onlyCNAME. It says:Unable to add record: A CNAME record is not allowed to coexist with any other data.NGINXI followedthis guideand tried redirecting it with sites-available config. Http and Https work, but www does not redirect to non-www.server {
# Redirect http to https
listen 80;
return 301 https://$host$request_uri;
}
server {
# Redirect www to non-www
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
server {
listen 443 ssl default_server;
ssl on;
ssl_certificate /etc/nginx/ssl/cert_chain.crt;
ssl_certificate_key /etc/nginx/ssl/example_com.key;
ssl_protocols TLSv1.1 TLSv1.2;
server_name example.com;
... | DNS Records Redirect www to non-www |
It's not exactly what I asked, but I think it'll work for my purposes. I'm still curious how to interpolate a variable inside a nginx PCRE regex if anyone else knows!set $chk == "need";
set $me "kevin";
if ($uri ~ /by-([^-]+)/) { set $by $1; }
if ($by = $me) {set $chk "";} | I have a caching system I need to bypass if the user's name (in a cookie) is found in the $request_uri. I'm trying to do something like this, but can't get the variable to interpolate into the regex. Any suggestions pretty please?I can set the $me variable just fine from the cookie; I just can't get it to interpolate into the regex.set $chk == "need";
set $me "kevin";
if ($uri ~ $me) { set $chk ""; }
if ($chk == "need") { rewrite ^ /testing }I've always tried things like this:if ($uri ~ "by-{$me}") { set $chk ""; }Thanks!
-Kevin | how to use a variable inside a nginx "if" regular expression |
On CentOS (tested on 7.x):Create file/etc/systemd/system/nginx.service.d/override.confwith the following contents:[Service]
LimitNOFILE=65536Reload systemd daemon with:systemctl daemon-reloadAdd this to Nginx config file:worker_rlimit_nofile 16384; (has to be smaller or equal to LimitNOFILE set above)And finally restart Nginx:systemctl restart nginxYou can verify that it works withcat /proc//limits. | Though I have done the following setting, and even restarted the server:# head /etc/security/limits.conf -n2
www-data soft nofile -1
www-data hard nofile -1
# /sbin/sysctl fs.file-max
fs.file-max = 201558The open files limitation of specific process is still 1024/4096:# ps aux | grep nginx
root 983 0.0 0.0 85872 1348 ? Ss 15:42 0:00 nginx: master process /usr/sbin/nginx
www-data 984 0.0 0.2 89780 6000 ? S 15:42 0:00 nginx: worker process
www-data 985 0.0 0.2 89780 5472 ? S 15:42 0:00 nginx: worker process
root 1247 0.0 0.0 11744 916 pts/0 S+ 15:47 0:00 grep --color=auto nginx
# cat /proc/984/limits
Limit Soft Limit Hard Limit Units
Max cpu time unlimited unlimited seconds
Max file size unlimited unlimited bytes
Max data size unlimited unlimited bytes
Max stack size 8388608 unlimited bytes
Max core file size 0 unlimited bytes
Max resident set unlimited unlimited bytes
Max processes 15845 15845 processes
Max open files 1024 4096 files
Max locked memory 65536 65536 bytes
Max address space unlimited unlimited bytes
Max file locks unlimited unlimited locks
Max pending signals 15845 15845 signals
Max msgqueue size 819200 819200 bytes
Max nice priority 0 0
Max realtime priority 0 0
Max realtime timeout unlimited unlimited usI've tried all possible solutions from googling but in vain. What setting did I miss? | How to set nginx max open files? |
Check if the upstream source has gzip turned on, if so you needproxy_set_header Accept-Encoding "";so the whole thing would be something likelocation / {
proxy_set_header Accept-Encoding "";
proxy_pass http://upstream.site/;
sub_filter_types text/css;
sub_filter_once off;
sub_filter .upstream.site special.our.domain;
}Check these linkshttps://www.ruby-forum.com/topic/178781https://forum.nginx.org/read.php?2,226323,226323http://www.serverphorums.com/read.php?5,542078 | I am trying to reverse proxy my website and modify the content.
To do so, I compiled nginx with sub_filter.
It now accepts the sub_filter directive, but it does not work somehow.server {
listen 8080;
server_name www.xxx.com;
access_log /var/log/nginx/www.goparts.access.log main;
error_log /var/log/nginx/www.goparts.error.log;
root /usr/share/nginx/html;
index index.html index.htm;
## send request back to apache1 ##
location / {
sub_filter 'test';
sub_filter_once on;
proxy_pass http://www.google.fr;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_redirect off;
proxy_buffering off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}Please help me | http_sub_module / sub_filter of nginx and reverse proxy not working |
Solved it by changing proxy_hide_header values in/etc/nginx/sites-available/defaultfile like so:proxy_hide_header X-Frame-Options;Needed to restartnginxas well as usepm2to restart mynodejsserver (for some reason, it didn't work till I made a small change to my server and restarted it). | I'm usingnginxas a reverse proxy for my website.I want to be able to open my website in aniFramefrom a chrome extension new tab html file.For this, I need mynginxto setX-Frame-Optionsto allowalldomains.According tothis answer, all domains is the default state if you don't set X-Frame-Options.My/etc/nginx/nginx.confdoesn't have the X-Frame-Options set anywhere.Yet when I check my website response header using Postman, it shows meX-Frame-Options = SAMEORIGIN.How can I remove this setting and load my website in an iFrame in the chrome new-tab .html file? | X-Frame-Options in nginx to allow all domains |
Quoting theman pageand assuming you have a Combined Log Format:If we would like to process all access.log.*.gz we can do one of the following:# zcat -f access.log* | goaccess --log-format=COMBINEDOR# zcat access.log.*.gz | goaccess --log-format=COMBINEDOn Mac OS X, usegunzip -cinstead ofzcat. | I want to parse all my logs of nginx (you can see here):ls /var/log/nginx/
access.log access.log.21.gz error.log.1 error.log.22.gz
access.log.1 access.log.22.gz error.log.10.gz error.log.23.gz
access.log.10.gz access.log.23.gz error.log.11.gz error.log.24.gz
access.log.11.gz access.log.24.gz error.log.12.gz error.log.2.gz
access.log.12.gz access.log.2.gz error.log.13.gz error.log.3.gz
access.log.13.gz access.log.3.gz error.log.14.gz error.log.4.gz
access.log.14.gz access.log.4.gz error.log.15.gz error.log.5.gz
access.log.15.gz access.log.5.gz error.log.16.gz error.log.6.gz
access.log.16.gz access.log.6.gz error.log.17.gz error.log.7.gz
access.log.17.gz access.log.7.gz error.log.18.gz error.log.8.gz
access.log.18.gz access.log.8.gz error.log.19.gz error.log.9.gz
access.log.19.gz access.log.9.gz error.log.20.gz
access.log.20.gz error.log error.log.21.gzbut I don't know how to do that. First of all, it seems like goaccess can't parse .gz files.What's the best way of parse all the information contained in these logs? | How to parse several log nginx files using goaccess |
No, they are not needed if you define your server blocks properly in nginx.conf, but it's highly suggested. As you noticed, they are only used because of theinclude /etc/nginx/sites-enabled/*;in nginx.conf.For curiosity, is there a reason why you do not want to use them? They are very useful; easier to add new sites, disabling sites, etc. Rather than having one large config file. This is a kind of a best practice of nginx folder layout. | I noticed my install of nginx has three folders calledetc/nginx/sites-available
etc/nginx/sites-enabled
etc/nginx/conf.dDo I really need these if I just want to work directly in theetc/nginx/nginx.conffile and remove theincludelines that include these items innginx.conf? Are these directories used for anything else that would mess things up if I delete them? | Nginx - Do I really need sites-available and sites-enabled folders? |
Add the following code to your Nginx Config, as detailed in the VueRouter docs,here:location / {
try_files $uri $uri/ /index.html;
}Also, you need to enable history mode on VueRouter:const router = new VueRouter({
mode: 'history',
routes: [...]
}) | I want to build a single page application with Vue.js using Nginx as my webserver and a my own Dropwiward REST API. Moreover I use Axios to call my REST request.My nginx config looks likeserver {
listen 80;
server_name localhost;
location / {
root path/to/vue.js/Project;
index index.html index.htm;
include /etc/nginx/mime.types;
}
location /api/ {
rewrite ^/api^/ /$1 break;
proxy_pass http://localhost:8080/;
}
}Currently I can just call mylocalhost/api/path/to/rescourceto get the the information from the backend.I build the Front end with HTML and javascript(vue.js) which has worked so far. However when I want to build a single page application most tutorials mention node.js. How can I use Nginx instead? | How to use vue.js with Nginx? |
Your rewrite statement is wrong.The $1 on the right refers to a group (indicated by paratheses) in the matching section.Try:rewrite ^/Shep.ElicenseWeb/(.*) /$1 break; | I'm trying to implement nginx rewrite rules for the following situationRequest:http://192.168.64.76/Shep.ElicenseWeb/Public/OutputDocuments.ashx?uinz=12009718&iinbin=860610350635Should be redirected to:http://localhost:82/Public/OutputDocuments.ashx?uinz=12009718&iinbin=860610350635I tried this with no luck:location /Shep.ElicenseWeb/ {
rewrite ^/Shep.ElicenseWeb/ /$1 last;
proxy_pass http://localhost:82;
}What is the correct way to perform such a rewrite for nginx ? | Nginx rewrite rule with proxy pass |
When running under nginx, you should use ngx.log. E.g:ngx.log(ngx.STDERR, 'your message here')For a working example, seehttp://linuxfiddle.net/f/77630edc-b851-487c-b2c8-aa6c9b858ebbFor documentation, seehttp://wiki.nginx.org/HttpLuaModule#ngx.log | I want to insert log points (io.write) inside my lua code which itself is in nginx configuration (using HttpLuaModule for nginx).
How to do that?
Access and error logs are not showing them. | How to debug lua code inside nginx config? |
Theproxy_set_header HEADER ""does exactly what you expect. Seehttps://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header.If the value of a header field is an empty string then this field will not be passed to a proxied server:proxy_set_header Accept-Encoding "";I have just confirmed this is working as documented, I used Nginx v1.12. | The Upstream server is wowza , which does not accept the custom headers if I don't enable them on application level.Nginx is working as a proxy server, from the browser I want to send few custom headers which should be received and logged by Nginx Proxy but before forwarding request to upstream server those headers should be removed from the request.So upstream server never come to know that there where any custom headers.I triedproxy_hide_headeras well asproxy_set_header "" "", but seems like they apply to response headers not the request headers.And even if I accept to enable the headers on wowza, then again I am not able to find a way to enable headers at server level for all application. Currenlty I have to add headers to each newly created application which is not feasible for me to do.Any help would be appreciated. | How to Remove Client Headers in Nginx before passing request to upstream server? |
After tryouts I found that this is only related to Cloudflare. Because I had no redirect problem before moving to Cloudflare.In my case it was a simple fix like this. Select [Crypto] box and select Full (strict) as in the image.Really, you can try this out first before any other actions. | I'm trying to set up NGINX and cloudflare.I've read about this on Google but nothing solved my problem. My cloudflare is active at the moment. I removed all page rules in cloudflare but before had domain.com and www.domain.com to use HTTPS. I thought this could be causing the problem so I removed it. Here is mydefaultNGINX file, with purpose of allowing only access by domain name and forbid access by IP value of the website:server{
#REDIRECT HTTP TO HTTPS
listen 80 default;
listen [::]:80 default ipv6only=on; ## listen for ipv6
rewrite ^ https://$host$request_uri? permanent;
}
server{
#REDIRECT IP HTTPS TO DOMAIN HTTPS
listen 443;
server_name numeric_ip;
rewrite ^ https://www.domain.com;
}
server{
#REDIRECT IP HTTP TO DOMAIN HTTPS
listen 80;
server_name numeric_ip;
rewrite ^ https://www.domain.com;
}
server {
listen 443 ssl;
server_name www.domain.com domain.com;
#rewrite ^ https://$host$request_uri? permanent;
keepalive_timeout 70;
ssl_certificate /ssl/is/working.crt;
ssl_certificate_key /ssl/is/working.key;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
#ssl_dhparam /path/to/dhparam.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM$
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security max-age=15768000;
(...) more ssl configsWhat could be off? I'll provide mroe information if needed... | Cloudflare and nginx: Too many redirects |
FINAL SOLUTIONSo that's what I found out:Flush would not work under Apache's mod_gzip or Nginx's gzip because, logically, it is gzipping the content, and to do that it must buffer content to gzip it. Any sort of web server gzipping would affect this. In short, at the server side, we need to disable gzip and decrease the fastcgi buffer size. So:In php.ini:. output_buffering = Off. zlib.output_compression = OffIn nginx.conf:. gzip off;. proxy_buffering off;Also have this lines at hand, specially if you don't have acces to php.ini:@ini_set('zlib.output_compression',0);@ini_set('implicit_flush',1);@ob_end_clean();set_time_limit(0);Last, if you have it, coment the code bellow:ob_start('ob_gzhandler');ob_flush();PHP test code:ob_implicit_flush(1);
for($i=0; $i<10; $i++){
echo $i;
//this is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
sleep(1);
}Related:php flush not workingHow to flush output after each `echo` call?PHP flushing output as soon as you call echo | Is it possible to echo each time the loop is executed? For example:foreach(range(1,9) as $n){
echo $n."\n";
sleep(1);
}Instead of printing everything when the loop is finished, I'd like to see it printing each result per time. | PHP Flush that works... even in Nginx |
Since you are using cloudflare flexible SSL your nginx config file wll look like this:-server {
listen 80 default_server;
listen [::]:80 default_server;
server_name mydomain.com www.mydomain.com;
if ($http_x_forwarded_proto = "http") {
return 301 https://$server_name$request_uri;
}
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
} | I have a website running on a LEMP stack. I have enabled cloudflare with the website. I am using the cloudflare flexible SSL certificate for https. When i open the website in chrome it shows website redirected you too many times and in firefox has detected that the server is redirecting the request for this address in a way that will never complete. I have tried to see answers of other questions but none of them seem to solve the problem. NGINX conf file:-server {
listen 80 default_server;
listen [::]:80 default_server;
server_name mydomain.com www.mydomain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}I would be highly grateful if anyone can point out what I am doing wrong. | HTTP to HTTPS Nginx too many redirects |
It appears the user nginx is running as (nginx?) is missing privileges to read the local file/home/ubuntu/virtualenv/myapp/myapp/homelaunch/static/img/templated/home/img.png. You probably wanna check file permissions as well as permissions on the directories in the hierarchy. | I have a django app, python 2.7 with gunicorn and nginx.Nginx is throwing a403 Forbidden Error, if I try to view anything in mystaticfolder @:/home/ubuntu/virtualenv/myapp/myapp/homelaunch/staticnginx config(/etc/nginx/sites-enabled/myapp) contains:server {
listen 80;
server_name *.myapp.com;
access_log /home/ubuntu/virtualenv/myapp/error/access.log;
error_log /home/ubuntu/virtualenv/myapp/error/error.log warn;
connection_pool_size 2048;
fastcgi_buffer_size 4K;
fastcgi_buffers 64 4k;
root /home/ubuntu/virtualenv/myapp/myapp/homelaunch/;
location /static/ {
alias /home/ubuntu/virtualenv/myapp/myapp/homelaunch/static/;
}
location / {
proxy_pass http://127.0.0.1:8001;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
}
}error.log contains:2013/11/24 23:00:16 [error] 18243#0: *277 open() "/home/ubuntu/virtualenv/myapp/myapp/homelaunch/static/img/templated/home/img.png" failed (13: Permission denied), client: xx.xx.xxx.xxx, server: *.myapp.com, request: "GET /static/img/templated/home/img2.png HTTP/1.1", host: "myapp.com", referrer: "http://myapp.com/"access.log containsxx.xx.xx.xxx - - [24/Nov/2013:23:02:02 +0000] "GET /static/img/templated/base/animg.png HTTP/1.1" 403 141 "http://myapp.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0"
xx.xx.xx.xxx - - [24/Nov/2013:23:02:07 +0000] "-" 400 0 "-" "-"I tried just viewing say a.cssfile in/static/and it throws an error like this in source:
403 Forbidden
403 Forbidden
nginx/1.1.19
| Nginx is throwing an 403 Forbidden on Static Files |
I finally found the solution: I need to pass$request_uriparameter:location / {
proxy_pass http://tracking/webapp$request_uri;
}That way, characters that were encoded in the original request willnotbe decoded, i.e. will be passed as-is to the proxied server. | I use nginx as a load balencer in front of several tomcats. In my incoming requests, I have encoded query parameters. But when the request arrives to tomcat, parameters are decoded :incoming request to nginx:curl -i "http://server/1.1/json/T;cID=1234;pID=1200;rF=http%3A%2F%2Fwww.google.com%2F"incoming request to tomcat:curl -i "http://server/1.1/json/T;cID=1234;pID=1200;rF=http:/www.google.com/"I don't want my request parameters to be transformed, because in that case my tomcat throws a 405 error.My nginx configuration is the following :upstream tracking {
server front-01.server.com:8080;
server front-02.server.com:8080;
server front-03.server.com:8080;
server front-04.server.com:8080;
}
server {
listen 80;
server_name tracking.server.com;
access_log /var/log/nginx/tracking-access.log;
error_log /var/log/nginx/tracking-error.log;
location / {
proxy_pass http://tracking/webapp;
}
}In my current apache load balancer configuration, I have theAllowEncodedSlashesdirective that preserves my encoded parameters:AllowEncodedSlashes NoDecodeI need to move from apache to nginx.My question is quite the opposite from this question :Avoid nginx escaping query parameters on proxy_pass | Avoid nginx decoding query parameters on proxy_pass (equivalent to AllowEncodedSlashes NoDecode) |
Had a similar problem, after a lot of searching the answer presented itself in therewrite docs.If you specify a ? at the end of a rewrite then Nginx will drop the original $args (arguments)So for your example, this would do the trick:location ^~ /mypage.php {
rewrite ^/mypage.php$ http://www.example.com/mypage? permanent;
} | I'm rewriting URLs in nginx after a relaunch. In the old site I had query parameters in the URL to filter stuff e.g.http://www.example.com/mypage.php?type=4The new page doesn't have these kind of parameters. I want to remove them and rewrite the URLs to the main page, so that I get:http://www.example.com/mypage/My rewrite rule in nginx is:location ^~ /mypage.php {
rewrite ^/mypage.php$ http://www.example.com/mypage permanent;
}But with this rule the parameter is still appended. I thought the$would stop nginx from processing further values... any ideas? All other questions deal with how to add parameters - I just want to remove mine :) | Remove parameters within nginx rewrite |
Celery and RQ is overengineering forsimple task.
Take a look at this docs -https://docs.python.org/3/library/concurrent.futures.htmlAlso check example, how to run long-running jobs in background for Flask app -https://stackoverflow.com/a/39008301/5569578 | I have a web-service that runs long-running jobs (in the order of several hours). I am developing this using Flask, Gunicorn, and nginx.What I am thinking of doing is to have the route which takes a long time to complete, call a function that creates a thread. The function will then return a guid back to the route, and the route will return a url (using the guid) that the user can use to check progress. I am making the thread a daemon (thread.daemon = True) so that the thread exits if my calling code exits (unexpectedly).Is this the correct approach to use? It works, but that doesn't mean that it is correct.my_thread = threading.Thread(target=self._run_audit, args=())
my_thread.daemon = True
my_thread.start() | How do I run a long-running job in the background in Python |
You can create a ConfigMap object and then mount the values as files where you need them:apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
data:
nginx.conf: |
your config
comes here
like this
other.conf: |
second file
contentsAnd in you pod spec:spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- name: nginx-config
mountPath: /etc/nginx/nginx.conf
subPath: nginx.conf
- name: other.conf
mountPath: /etc/nginx/other.conf
subPath: other.conf
volumes:
- name: nginx-config
configMap:
name: nginx-config(Take note of the duplication of the filename in mountPath and using the exact same subPath; same as bind mounting files.)For more information about ConfigMap see:https://kubernetes.io/docs/user-guide/configmap/Note: A container using a ConfigMap as a subPath volume will not receive ConfigMap updates. | How can I pass thenginx.confconfiguration file to an nginx instance running inside a Kubernetes cluster? | Add nginx.conf to Kubernetes cluster |
Great question, with the solutionsimilar to another one I've answered on ServerFault recently, although it's much simpler here, and you know exactly what you need.What you want here is to only perform the redirect when the user explicitly requests/index.php, but never redirect any of the internal requests that end up being served by the actualindex.phpscript, as defined through theindexdirective.This should do just that, avoiding the loops:server {
index index.php;
if ($request_uri ~* "^(.*/)index\.php$") {
return 301 $1;
}
location / {
# ...
}
} | I want any requests likehttp://example.com/whatever/index.php, to do a 301 redirect tohttp://example.com/whatever/.I tried adding:rewrite ^(.*/)index.php$ $1 permanent;
location / {
index index.php;
}The problem here, this rewrite gets run on the root url, which causes a infinite redirect loop.Edit:I need a general solutionhttp://example.com/should serve the filewebroot/index.phphttp://example.com/index.php, should 301 redirect tohttp://example.com/http://example.com/a/index.phpshould 301 redirect tohttp://example.com/a/http://example.com/a/should serve the index.php script atwebroot/a/index.phpBasically, I never want to show "index.php" in the address bar. I have old backlinks that I need to redirect to the canonical url. | nginx redirect loop, remove index.php from url |
You might what to try setting theumaskbefore callingfile_put_contents: it will change the default permissions that will be given to the file when it's created.The other way (better, according to the documentation) is to usechmodto change the permissions, just after the file has been created.Well, after re-reading the question, I hope I understood it well... | I am usingfile_put_contentsto create a file. My php process is running in a group with permissions to write to the directory. Whenfile_put_contentsis called, however, the resulting file does not have group write permissions (it creates just fine the first time). This means that if I try to overwrite the file it fails because of a lack of permissions.Is there a way to create the file with group write permissions? | how can I create a file with file_put_contents that has group write permissions? |
1) ensure you have Nginx > 1.2.x (to proper headers modifications) and compile with--with-http_gzip_static_moduleoption2) Enable this optiongzip on(to serve back-end response with gzip header)3) Setup assets location withgzip_static on(to serveall.css.gz, all.js.gzfiles directly)4) Prevent of etag generation and last-modify calculation for assets5) Turn on the right Cache-control to cache SSL served static assets,
unless they will be expired once browser is closedlocation ~ ^/(assets|images|javascripts|stylesheets|swfs|system)/ {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header Last-Modified "";
add_header ETag "";
}if you would like to get full Nginx configuration, you can seethis gist on Github.open_file_cachehelps you to cache: open file descriptors, their sizes, modification times and directory lookups, which is helpful for high load on the file system.UPDATE:If you are living on the edge, turn on the SPDY to boost the SSL connection. | Rails 3.1 has a convenient system which can compress files into .gz files. However, instead what I've done is I've moved all the asset files that are created with assets:precompile to a static webserver. This all works, but how can I get nginx to serve the .gz files normally? | Get NGINX to serve .gz compressed asset files |
You are missing theProxyFix()middleware component. See the FlaskProxy Setups documentation.There is no need to subclass anything; simply add this middleware component to your WSGI stack:# Werkzeug 0.15 and newer
from werkzeug.middleware.proxy_fix import ProxyFix
from flask import Flask
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1)If you have Flask installed, you have Werkzeug too, but do pin the version to >=0.15 to get the updated version ofProxyFix(Flask 1.1.0 and newer already use that version).This componentsets the WSGI scheme from the X-Forwarded-Proto header. Do read the Flask documentation I linked you to above about trusting headers and about customising the middleware to your specific situation. Above, I’ve configured it to only look atX-Forwarded-Proto, but the component can handle otherX-Forwarded-*configurations too.The default is to trust one level ofX-Forwarded-For, addx_for=0to the keyword arguments if you want to disable this.Also note that the functionality of theProxyFixmiddleware has been expanded quite significantly in Werkzeug 0.15; in addition toX-Forwarded-Proto,-For, and-Host, theX-Forwarded-Portand-Prefixheaders are also consulted, all headers support multiple values. | I have precisely the same problem described inthis SO question and answer. The answer to that question is a nice work around but I don't understand the fundamental problem. Terminating SSL at the load balancer and using HTTP between the load balancer and web/app servers is very common. What piece of the stack is not respecting the X-Forwarded-Proto? Is it werkzeug? Flask? uwsgi?In my case I'm using an AWS ELB (which sets X-Forwarded-Proto) => Nginx (which forwards along X-Forwarded-Proto to uwsgi). But in the python app I have to subclass Flask Request as described in the question I referenced above.Since this is such a common deployment scenario, it seems that there should be a better solution. What am I missing? | X-Forwarded-Proto and Flask |
Your ingress definition creates rules that proxy traffic from the{path}to the{backend.serviceName}{path}. In your case, I believe the reason it's not working is that/appis proxied toapp-service:80/appbut you're intending on serving traffic at the/root. Try adding this annotation to your ingress resource:nginx.ingress.kubernetes.io/rewrite-target: /Source:https://github.com/kubernetes/ingress-nginx/tree/master/docs/examples/rewrite | I have the following that config that works when I try:30080apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: app-deployment
spec:
replicas: 3
template:
metadata:
labels:
name: app-node
spec:
containers:
- name: app
image: myregistry.net/repo/app:latest
imagePullPolicy: Always
ports:
- containerPort: 8080
env:
- name: NODE_ENV
value: production
---
apiVersion: v1
kind: Service
metadata:
name: app-service
spec:
selector:
name: app-node
ports:
- protocol: TCP
port: 80
targetPort: 8080
nodePort: 30080
type: NodePortI am trying to use an Ingress:apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: nginx-ingress
spec:
rules:
- host: myhost.com
http:
paths:
- path: /app
backend:
serviceName: app-service
servicePort: 80myhost.comworks with the nginx intro screen, butmyhost.com/appgives404 Not Found. Where is the issue in my setup?UPDATE:- path: /
backend:
serviceName: app-service
servicePort: 80If I do root path it works, but how come/appdoesn't? | Kubernetes Ingress non-root path 404 Not Found |
I have found the solution. The problem was that there were multiple instances of nginx running. This was causing a conflict and that's why the large_client_header_buffers wasnt working. After killing all nginx instances I restarted nginx with the configuration:client_header_buffer_size 64k;
large_client_header_buffers 4 64k;Everything started working after that.Hope this helps anyone facing this problem. | I have a large URI and I am trying to configure Nginx to accept it. The URI parameters are 52000 characters in length with a size of 52kb. I have tried accessing the URI without Nginx and it works fine.But when I use Nginx it gives me an error. --- 414 (Request-URI Too Large)I have configured the large_client_header_buffers and client_header_buffer_size in the http block but it doesn't seem to be working.client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;Any help will be appreciated.Thank you. | Configuring Nginx for large URIs |
Herehttp://developer.yahoo.com/yui/theater/video.php?v=dahl-nodeNode.js author says that Node.js is still in development and so there may be security issues that NginX simply hides.On the other hand, in case of a heavy traffic NginX will be able to split the job between many Node.js running servers. | From what I understand Node.js doesnt need NginX to work as a http server (or a websockets server or any server for that matter), but I keep reading about how to use NginX instead of Node.js internal server and cant find of a good reason to go that way | What is the benefit of using NginX for Node.js? |
Reference:http://wiki.nginx.org/HttpRewriteModule#rewriteIf the replacement string begins with http:// then the client will be redirected, and any further >rewrite directives are terminated.So remove the http:// part and it should work:location ~ /[0-9]+ {
rewrite "/([0-9]+)" /v.php?id=$1 break;
} | I want to use rewrite function in my nginx server.When I try "http://www.example.com/1234", I want to rewrite "http://www.example.com/v.php?id=1234" and want to get "http://www.example.com/1234" in browser.Here is nginx.conf file...
location ~ /[0-9]+ {
rewrite "/([0-9]+)" http://www.example.com/v.php?id=$1 break;
}
...When I try "http://www.example.com/1234"I want to ...url bar in browser : http://www.example.com/1234
real url : http://www.example.com/v.php?id=1234but I'm in trouble ...url bar in browser : http://www.example.com/v.php?id=1234
real url : http://www.example.com/v.php?id=1234 | nginx rewrite WITHOUT change url |
It is possible since nginx 1.9.0:http://nginx.org/en/docs/stream/ngx_stream_core_module.htmlSomething along these lines (this goes on top level ofnginx.conf):stream {
upstream backend {
server backend1.example.com:12345;
}
server {
listen 12345;
proxy_pass backend;
}
} | I have nginx running on my server, listening port 80 and 433. I know nginx has a number ways of port forwarding that allows me to forward request like:http://myserver:80/subdir1to some address like:http://myserver:8888.My question is it possible to configure nginx so that i can forwardNON-http request (just thoseplain TCP connection) to some other port? It's very easy to test if it's a http request because the first bytes will be either "GET" or "POST". Here's the example.The client connected to nginx .
The client send:a. HTTP get request: "GET / HTTP 1.1": some rule for HTTPb. Any bytes that can't be recognized as HTTP header: forward it to some other port, say, 888, 999, etc.Is it technically possible? Or would you suggest a way to do this? | Is it possible to forward NON-http connecting request to some other port in nginx? |
Yourps ... | egrepcommand is finding itself, not an instance of nginx (look at the "COMMAND" column). Since port 80 is in use, it's likely some other program (maybe the Apache that comes with the OS?) is running and grabbing it. To find out, run:sudo lsof -i:80If it's the system Apache ("httpd") program, you can probably shut it down with:sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plistIf that doesn't do it, more info will be needed to figure out what's grabbing port 80 and how it's getting started. | I've been using nginx for a few months without issue, but after upgrading to Mac OS X 10.9 Mavericks, when trying to start nginx I get this:nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (48: Address already in use)
nginx: [emerg] still could not bind()I tried to followthese directions, but I'm not having much luck as my outputs seem a little different.The output of:ps ax -o pid,ppid,%cpu,vsz,wchan,command|egrep '(nginx|PID)'is:PID PPID %CPU VSZ WCHAN COMMAND
15015 12765 0.0 2432784 - egrep (nginx|PID)I've tried killing the process using that PID, but it never seems to die... Any ideas on how to get nginx running again? Any help is greatly appreciated!! | nginx startup fail on mac osx 10.9 mavericks |
The "sites-enabled" approach as used by some Linux packages of nginx utilizeincludedirective, which understands shell wildcards, seehttp://nginx.org/r/include. You may use it in your own config as well, e.g.http {
...
include /path/to/sites/*.conf;
}Note though that such approach might be very confusing (in particular, it would be hard to tell which server{} is the default one unless you usedefault_serverexplicitly). | I'm trying to set up Nginx on my Windows development environment. I can't find how to create something similar to"sites-enabled"on Linux where Nginx would look for (links to) active virtual host configurations.Is there a way to do something similar with a directory with shortcuts to the actual configuration files and Nginx scanning that directory? Or is there another way to hook up a virtual host configuration other than copying the host configuration tonginx.conf? | nginx Windows: setting up sites-available configs |
SetSERVER_NAMEto use$hostin yourfastcgi_paramsconfiguration.fastcgi_param SERVER_NAME $host;Source:http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_param | My configuration file has aserverdirective block that begins with...server {
server_name www.example1.com www.example2.com www.example3.com;...in order to allow the site to be accessed with different domain names.However PHP's$_SERVER['SERVER_NAME']always returns the first entry ofserver_name, in this casehttp://www.example1.comSo I have no way from the PHP code to know which domain the user used to access the site.Is there any way to tell nginx/fastcgi to pass the real domain name used to access the site?The only solution I've found so far is to repeat the entireserverblock for each domain with a distinctserver_nameentry but obviously I'm looking for a better one. | nginx "server" directive with multiple "server_name" entries: always first one is passed to PHP's $_SERVER['SERVER_NAME'] |
You can addlocationwith regexp:server {
listen 80;
server_name localhost;
location ~* \.(js|jpg|png|css)$ {
root path/to/tomcat/document/root/Test/;
expires 30d;
}
location / {
proxy_pass http://127.0.0.1:8081/Test/;
}
} | Recently I have started using NGINX, I found that we can use it for reverse proxy, serving static content from itself which can reduce load time. I have a Tomcat/JBoss server on my local machine and I want to put NGINX in front of it so that static content will be served from NGINX and rest all by Tomcat/JBoss. My Tomcat/JBoss application is running onhttp://localhost:8081/Testmy NGINX configuration worked properly but it is not able to loadcss/js/jpgfile. Here is my war strcuture wehere static contents areTest.warTEST
|
|--->Resources
| |------->CSS
| | |----> style.css
| |
| |-------->Images
| |----> a.jpg
| |----> b.jpg
|
|--->WEB-INF
| |----->Web.xml
| |----->spring-servlet.xml
|
|--->JSP
|---->login.jspI think the problem is because of absolute path, so should I copy resources folder and put it in some folder in NGINX and configure my NGINX to pick file from its own directory rather going to Tomcat/JBoss? I am new so I dont have any idea of doing this can anyone pls help me in this. This is my conf file for NGINX(windows)server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://127.0.0.1:8081/Test/;
} | how to make NGINX serve static content like .js, .css, .html? |
As the prefix is set in Nginx, the web server that hosts the Django app has no way of knowing the URL prefix. As orzel said, if you used apache+mod_wsgi of even nginx+gunicorn/uwsgi (with some additional configuration), you could use the WSGIScriptAlias value, that is automatically read by Django.When I need to use a URL prefix, I generally put it myself in my root urls.py, where I have only one line, prefixed by the prefix and including an other urls.py(r'^/myapp/', include('myapp.urls')),But I guess this has the same bottleneck than setting a prefix in settings.py, you have redundant configuration in nginx and Django.You need to do something in the server that hosts your Django app at :12345. You could set the prefix there, and pass it to Django using the WSGIScriptAlias or its equivalent outside mod_wsgi. I cannot give more information as I don't know how your Django application is run. Also, maybe you should consider running your Django app directly from Django, using uWSGI or gunicorn.To pass the prefix to Django from the webserver, you can use this :proxy_set_header SCRIPT_NAME /myapp;More informationhere | I have a django application running onhttp://localhost:12345.
I'd like user to access it via urlhttp://my.server.com/myapp.
I use nginx to reverse proxy to it like the following:... ...
server_name my.server.com;
location /myapp {
rewrite /myapp(.*) $1 break;
... ... # proxy param
proxy_pass http://localhost:12345;
}
... ...The question is, when configured like the above, how to make the urls in my response pages to have a prefix of "/myapp" so that the nginx can direct them correctly to myapp. E.g., the urls in a page like "/foo/far" ought to be changed to "/myapp/foo/bar" to allow nginx proxy to myapp.
what is the right nginx configure to use to achieve this ?I can use settings variables of django to specify the root url prefix, but it's not flexiable to my mind, since the variable have to be modified according to different nginx configuration(say one day nginx may change the suburl from "/myapp" to "/anotherapp"). | how to deploy django under a suburl behind nginx |
Your doing fine. I guess you are editing /etc/nginx/sites-enabled/default (or the linked file at /etc/nginx/sites-available/default.This is the standard nginx set up. It is configured with /etc/nginx/nginx.conf which contains the http {} statement. This in turn contains an "include /etc/nginx/sites-enabled/*" line to include your file above with server{ } clause in it.Note that if you are using an editor that creates a backup file, you must modify the include statement to exclude the backup files, or you will get some "interesting" errors! My line isinclude /etc/nginx/sites-enabled/*[a-zA-Z]which will not pick up backup files ending in a tilde. YMMV. | I am reading nginx beginner's tutorial, on the sectionServing Static Contentthey havehttp {
server {
}
}but when I add an http block I get the error[emerg] "http" directive is not allowed here …When I remove the http block and change the conf file to this, it works fine:server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /var/example.com/html;
index index.html index.htm;
# make site accessible from http://localhost/
server_name localhost
location / {
try_files $uri $uri/ /index.html;
}I suspect that I am missing something simple, but why do they use http to serve static files? | When do we need to use http block in nginx config file? |
I’ve faced the same issue and found the solution ongithub.
To achieve your goal, you need to create two Ingresses first by default without any restriction:apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-test
spec:
rules:
- host: host.host.com
http:
paths:
- path: /service-mapping
backend:
serviceName: /service-mapping
servicePort: 9042Then, create asecretfor auth as described in thedoc:Creating thehtpasswd$ htpasswd -c auth foo
New password:
New password:
Re-type new password:
Adding password for user fooCreating thesecret:$ kubectl create secret generic basic-auth --from-file=auth
secret "basic-auth" createdSecond Ingress with auth for paths which you need to restrict:apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-with-auth
annotations:
# type of authentication
nginx.ingress.kubernetes.io/auth-type: basic
# name of the secret that contains the user/password definitions
nginx.ingress.kubernetes.io/auth-secret: basic-auth
# message to display with an appropiate context why the authentication is required
nginx.ingress.kubernetes.io/auth-realm: "Authentication Required - foo"
spec:
rules:
- host: host.host.com
http:
paths:
- path: /admin
backend:
serviceName: service_name
servicePort: 80According tosedooe answer, his solution may have some issues. | I've a simple kubernetes ingress network.I need deny the access some critical paths like /admin or etc.My ingress network file shown as below.apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: ingress-test
spec:
rules:
- host: host.host.com
http:
paths:
- path: /service-mapping
backend:
serviceName: /service-mapping
servicePort: 9042How I can deny the custom path with kubernetes ingress network, with nginx annonations or another methods .I handle this issue with annotations shown as below .apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: nginx-configuration-snippet
annotations:
nginx.ingress.kubernetes.io/configuration-snippet: |
server_tokens off;
location DANGER-PATH {
deny all;
return 403;
}
spec:
rules:
- host: api.myhost.com
http:
paths:
- backend:
serviceName: bookapi-2
servicePort: 8080
path: PATH | Kubernetes Ingress network deny some paths |
All you need is themod_auth_sspiApache module.Sample configuration:AuthType SSPI
SSPIAuth On
SSPIAuthoritative On
SSPIDomain mydomain
# Set this if you want to allow access with clients that do not support NTLM, or via proxy from outside. Don't forget to require SSL in this case!
SSPIOfferBasic On
# Set this if you have only one domain and don't want the MYDOMAIN\ prefix on each user name
SSPIOmitDomain On
# AD user names are case-insensitive, so use this for normalization if your application's user names are case-sensitive
SSPIUsernameCase Lower
AuthName "Some text to prompt for domain credentials"
Require valid-userAnd don't forget that you can alsouse Firefox for transparent SSO in a Windows domain: Simply go toabout:config, search fornetwork.automatic-ntlm-auth.trusted-uris, and enter the host name or FQDN of your internal application (like myserver or myserver.corp.domain.com). You can have more than one entry, it's a comma-separated list. | I'm vaguely aware that on a computer joined to a domain IE can be asked to send some extra headers that I could use to automatically sign on to an application. I've got apache running on a windows server with mod_php. I'd like to be able to avoid the user having to log in if necessary. I've found some links talking about Kerberos and Apache modules.http://www.onlamp.com/pub/a/onlamp/2003/09/11/kerberos.html?page=lasthttps://metacpan.org/pod/Apache2::AuthenNTLMSince I'm running on Windows it's proven to be non-trivial to get Perl or Apache modules installed. But doesn't PHP already have access to HTTP headers?I found this but it doesn't do any authentication, it just shows that PHP can read the NTLM headers.http://siphon9.net/loune/2007/10/simple-lightweight-ntlm-in-php/I'd like to be able to have my users just point to the application and have them automatically authenticated. Has anyone had any experience with this or gotten it to work at all?UPDATESince originally posting this question, we've changed setups to nginx and php-fcgi still running on windows. Apache2 and php-cgi on windows is probably one of the slowest setups you could configure on windows. It's looking like Apache might still be needed (it works with php-fcgi) but I would prefer a nginx solution.I also still don't understand (and would love to be educated) why HTTP server plugins are necessary and we can't have a PHP, web server agnostic solution. | How can I implement single sign-on (SSO) using Microsoft AD for an internal PHP app? |
When you're starting with Docker you may find helpful information about images at DockerHub. For example with nginx you have a section about how toexpose public ports.You can just use:docker run --publish 3000:80 nginxPort 3000 in your localhost will be forwarded to port 80 which is the port that nginx images use to wait for http connections.I also recommend you to read these official docsabout networking in Docker. | I am a docker beginner and the first thing i did was download nginx and tried to mount it on 80:80 port but Apache is already sitting there.docker container run --publish 80:80 nginxanddocker container run --publish 3000:3000 nginxI tried doing it like this 3000:3000 to use it on port 3000 but it doesn't work .And it doesn't log anything either which i could use for referance. | How to change the port of nginx when using with docker |
The message means what it says. Thenginxexecutable was compiled to expect the PCRE (Perl-compatible Regular Expression) shared library to be available somewhere on LD_LIBRARY_PATH or specified in/etc/ld.so.confor whatever equivalent library-locating mechanisms apply to your operating system, and it cannot find the library.You will need to install PCRE - or configure your environment so thatnginxwill look for the PCRE library where it is installed. | I just installed Passenger 3.0.11 andnginxand got this error:Starting nginx: /opt/nginx/sbin/nginx: error while loading shared libraries: libpcre.so.0: cannot open shared object file: No such file or directory | Error while loading shared libraries: 'libpcre.so.0: cannot open shared object file: No such file or directory' |
If you're using nginx to handle SSL, then your node server will just be using http.upstream nodejs {
server 127.0.0.1:4545 max_fails=0;
}
server {
listen 443;
ssl on;
ssl_certificate newlocalhost.crt;
ssl_certificate_key newlocalhost.key;
server_name nodejs.newlocalhost.com;
add_header Strict-Transport-Security max-age=500;
location / {
proxy_pass http://nodejs;
proxy_redirect off;
proxy_set_header 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;
}
} | my nginx server is actually proxying my node backend (which listens on port 3000) with a simple:location /api/ {
proxy_pass http://upstream_1;
}Where upstream_1 is my node cluster defined in nginx.conf (on port 3000).I'm gonna have to add SSL over http connections, so I have the following question: do I only need to configure nginx to enable ssl? And it will automatically "uncrypt" the request and pass it uncrypted to Node which will be able to handle it normally? Or do I need to configure Nodejs to support ssl as well? | nginx proxy pass Node, SSL? |
That should work. Nginx should strip the '/test' path on the upstream local server. So what I can say is that is not the cause. To make it a bit better, try this:location /test/ {
proxy_pass http://localserver.com/;
}The 2 slashes I added at the first 2 lines will avoid mistakenly match '/testABC' and send the wrong request to the upstream local server, for example.Do you have aproxy_redirectline in the same location block? If your upstream local server has redirects, then a mistake on that line will cause an issue like you described.[UPDATE] Found the root cause why the original config didn't work and mine works: nginx does NOT replace URI path part if the proxy_pass directive does not have a URI path itself. So my fix of adding a slash (slash is treated as a URI path) at the end triggers the URI path replacement.Reference:http://wiki.nginx.org/HttpProxyModule#proxy_passIf it is necessary to transmit URI in the unprocessed form then directive proxy_pass should be used without URI partlocation /some/path/ {
proxy_pass http://127.0.0.1;
} | we have two servers, A and B. Server A is accessed worldwide. He has nginx installed. That's what I have in conf:location /test {
proxy_pass http://localserver.com;
}What it should do, is translate the addreesshttp://globalserver.com/test(that is server A) to internal server addresshttp://localserver.com. However, it does append the location path, that is, itries to look forhttp://localserver.com/test, which is not available at all. How can I make the proxy pass to the correct address, throwing out the last part in the location? | Correct proxy path in nginx.conf |
Becausesystemd is configured to give nginx a private /tmp. If youmustuse the system /tmp instead for some reason then you will need to modify the .service file to read "PrivateTmp=no". | I found strange behaviour concerningphpand/tmpfolder. Php uses another folder when it works with/tmp. Php 5.6.7, nginx, php-fpm.I execute the same script in two ways: via browser and via shell. But when it is launched via browser, file is not in real/tmpfolder: /tmp/'.$name.'.txt');
var_dump(file_exists('/tmp/'.$name.'.txt'));
var_dump(shell_exec('cat /etc/*release | tail -n 1'));php -f script.phpFile /tmp/185617.txt
bool(true)
string(38) "CentOS Linux release 7.0.1406 (Core)Where is the file? In /tmp$ find / -name 185617.txt
/tmp/185617.txtIf access it viahttp://myserver.ru/script.phpI getFile /tmp/185212.txt
bool(true)
string(38) "CentOS Linux release 7.0.1406 (Core)But where is the file?$ find / -name 185212.txt
/tmp/systemd-private-nABCDE/tmp/185212.txtWhy does php thinks that/tmpshould be in/tmp/systemd-private-nABCDE/tmp? | Php has its own /tmp in /tmp/systemd-private-nABCDE/tmp when accessed through nginx |
Writing non blocking applications in php is possible, but it's probably not the best environment to do so, as it wasn't created keeping that in mind! You get a pretty decent control over your child processes using the process control libraryPCNTLbut it obviously won't ever offer you same ease of use that other environments can give you!I don't know python very well but personally I'd recommended you go withnodejs! It's a fairly new technology, that's true, but everything is non blocking there and it's meant to be that way! Basically what you have is a single thread (which you can extend however you want in this news versions) and literally everything (except you tell it to do differently) is going to be event-driven, leaving space to proceed on the process queue as expected!Nodejs is really easy to learn, if you ever stumbled upon web applications, you know javascript anyways! it is still not hugely documented, but there are many ready to use modules you can download and use straight away! | I want to write non-blocking applications. I use apache2, but I was reading about nginx and its advantage with respect to apache processes. I am considering changing out apache for nginx. My question is, is it possible to write non-blocking web applications with php and nginx?.Or is a better idea to try and do this with python, using some reverse proxy like uwsgi or gunicorn with nginx? Or is the solution to learn nodejs? | Write PHP non blocking applications |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.