Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
The pattern you use requires the legacy DN, since it assumes the/to separate the RDNs. So (since nginx v1.11.6) the following works:map $ssl_client_s_dn_legacy $ssl_client_s_dn_cn {
default "";
~/CN=(?[^/]+) $CN;
}With $ssl_client_s_dn_legacy: /O=Test Organization/CN=testcn | I need to get the CN of a client certificate in NGINX to append it to the proxy headers.I already found the following map code for this.map $ssl_client_s_dn $ssl_client_s_dn_cn {
default "";
~/CN=(?[^/]+) $CN;
}But sadly it only returns an empty string for the following $ssl_client_s_dn:
CN=testcn,O=Test OrganizationI tested it with other DNs, too. But the problem is always the same. | Getting Common Name from Distinguished Name of client certificate in NGINX |
Not specifically a fix for Angular/nginx, but a practice I often use is to append a query string parameter to the resource when you load it. For me, this is typically derived from version number of the .js file / application, e.g. using it as a seed for a RNGSo, instead of:useBonus points- in your Angular application, you can keep track of what version of the assets that you want to include, meaning that you can release new asset files without having clients immediately update to them if they have them in local cache (although note that new clients will get the new version regardless) | I'm using angular with i18n translations in json files like de.json and en.json. In my production environment (nginx) I have the problem that these JSON files are cached by the web browser. After an upgrade, Chrome will not download the new version of the current json file even though the date header has changed.Request Information (Chrome):Request URL:https://[my-site]/assets/i18n/de.jsonRequest Method: GETStatus Code: 200 (from disk cache)Remote Address: X.X.X.X:443Referrer Policy: no-referrer-when-downgradeResponse Headers:content-encoding: gzipcontent-type: application/jsondate: Fri, 15 Feb 2019 09:04:42 GMTetag: W/"5c62bf4d-2aea"last-modified: Tue, 12 Feb 2019 12:42:53 GMTserver: nginx/1.14.0 (Ubuntu)status: 304Does anyone have experience with this problem and can help me? | Angular i18n json cache issues using nginx |
You don't really need aStatefulSet, aDeploymentwill do since nginx is already being fronted by a gcloud TCP load balancer, if for any reason one of your nginx pods is down the gcloud load balancer will not forward traffic to it. Since you already have a gcloud load balancer you will have to use aNodePortServicetype and you will have to point your gcloud load balancer to all the nodes on your K8s cluster on that specific port.Note that yournginx.confwill have to know how to route to all the services internally in your K8s cluster. I recommend you set up annginx ingress controller, which will basically manage thenginx.conffor you through anIngressresource and you can also expose it as aLoadBalancerService type. | I have some services running in Kubernetes. I need an NGINX in front of them, to redirect traffic according to the URLs, handle SSL encryption and load balancing.There is a working nginx.conf for that scenario. What I´m missing is the right way to set up the architecture on gcloud.Is it correct to launch a StatefulSet with nginx and have a Loadbalancing Service expose NGINX? Do I understand it right, that gcloud LB would pass the configured Ports ( f.e. 80 + 443) to my NGINX service, where I can handle the rest and forward the traffic to the backend services? | NGINX loadbalancing on Kubernetes |
I already solved the problem.
First you should comment out this line or remove this line from thesnippets/fastcgi-php.conffiletry_files $fastcgi_script_name =404;then on your virtualhost config puttry_files $uri $uri /index.php;before theinclude snippets/fastcgi-php.conf;on thelocation ~\.php$block.thelocation ~\.php$block should look like this:location ~ \.php$ {
try_files $uri $uri /index.php;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}that should do the trick. | I have this nginx vhost config:server {
listen 8081;
server_name blocked_server;
root /home/gian/blocked_server;
access_log off;
error_log off;
index index.php index.html index.htm index.nginx-debian.html;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
location ~ / {
try_files $uri $uri /index.php;
}
}it redirects all urls to index.php except when the url ends with .php extension.for example this works:http://localhost/somethingthatdontexistbut this returns a 404 and don't redirect to index.phphttp://localhost/somethingthatdontexist.phphow can i redirect url with .php extension that don't exist to index.php? | How to redirect all request to index.php even with .php in the url |
I discovered that there was a discrepancy with/etc/nginx/nginx.confI had the user set as www-data and I should have set it as crawforc3. Making this change and restarting nginx and gunicorn resolved the issue. | I am trying to setup a simple flask application served by Nginx and Gunicorn and have mostly followed thistutorial. When trying to access the webpage, I get a 502 Bad Gateway error.The nginx log (/var/log/nginx/error.log) says :[crit] 23472#0: *1 connect() to unix:/home/crawforc3/webpage/webpage.sock failed (13: Permission denied)I checked and there is awebpage.sockfile in my project directory that looks like this:srwxrwxrwx 1 crawforc3 www-data 0 May 31 17:59 webpage.sockHere is my/etc/systemd/system/gunicorn.service[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=crawforc3
Group=www-data
WorkingDirectory=/home/crawforc3/webpage
Environment="PATH=home/crawforc3/miniconda3/envs/HALSWEBPAGE/bin"
ExecStart=/home/crawforc3/miniconda3/envs/HALSWEBPAGE/bin/gunicorn --workers 3 --bind unix:/home/crawforc3/webpage/webpage.sock -m 007 wsgi:app
[Install]
WantedBy=multi-user.target | Serving flask application with Nginx and gunicorn: permission denied when connecting to webpage.sock |
The problem was that my client key was also including signing certificates in key chain. Not only my client certificate (which is required for authentication), but whole chain of certificates (without keys of course, just certificates)It was:> Root CA cert -> Client CA cert -> Client key + certI guess Java uses a wrong certificate at this case, maybe CA or intermediate certificate.Fixed by adding top12orkeychainonly client's key and certificate, without intermediates.Itshould nothave-certfileoptions (which I had before). Just client key/cert. Correct export command is:openssl pkcs12 -export \
-in client.crt -inkey client.key \
-out client.p12Thisclient.p12then could be imported into keychain:keytool -importkeystore \
-deststorepass changeit -destkeystore keystore \
-srckeystore client.p12 -srcstoretype PKCS12 -srcstorepass changeitAnd worked fine for custom authentication. | Trying to implement client key authentication (with self signed ca).Code looks like:KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("client.p12"), "changeit".toCharArray())
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy()) //DONT DO THAT, IT'S JUST TO SIMPLIFY THIS EXAMPLE. USE REAL TrustStore WITH REAL SERVER CERTIFICATE IMPORTED. DONT TRUST SELF SIGNED
.loadKeyMaterial(keyStore, "changeit".toCharArray())
.build();
socketFactory = new SSLConnectionSocketFactory(
sslcontext,
new String[] {"TLSv1.2", "TLSv1.1"},
null,
new NoopHostnameVerifier()
);
HttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(socketFactory)
.build();With-Djavax.net.debug=allI can see it correctly chooses my certificate, i see signatures, I see certificate request, and there ECDHClientKeyExchange, etc, all looks fine.But anyway I'm getting following response from Nginx (with status 400):400 The SSL certificate errorNotice, that for incorrect certificate/key nginx usually drops session, w/o providing any details in plain text response.Thisclient.p12works from command line, like:$ curl -ivk --cert client.p12:changeit https://192.168.1.1
* Rebuilt URL to: https://192.168.1.1/
* Trying 192.168.1.1...
* Connected to 192.168.1.1 (192.168.1.1) port 443 (#0)
* WARNING: SSL: Certificate type not set, assuming PKCS#12 format.
* Client certificate: client-es.certs.my
* TLS 1.2 connection using TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
* Server certificate: server.certs.my
* Server certificate: ca.my
> GET / HTTP/1.1
> Host: 192.168.1.1
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 200 OKSo this key is definitely valid. But why it doesn't work for Java? Is there're anything i've missed in java ssl config? | Client authentication with HttpClient |
The instructions mention:put your Symfony application intosymfonyfolderand do not forget to addsymfony.devin your/etc/hostsfile.Then, run:$ docker-compose upYou are done,you can visite your Symfony application on the following URL:http://symfony.dev(and access Kibana onhttp://symfony.dev:81)That "symfonyfolder" comes fromdocker-compose.yml#L4volumes:
- ./symfony:/var/www/symfonyIt means you should create asymfonyfolder in yourdocker-symfonycloned repo, which will be mounted as/var/www/symfonyin the application container.docker-symfony
code
elk/logstash
nginx
php-fpm
.gitignore
.travis.yml
README.md
symfony <====== Add your folder thereThat folder can be a symbolic link to wherever you have yoursymfonyproject. | I git cloned this repository:docker-symfonyand followed the installation instructions.When I visitedsymfony.dev:81, I saw kibana 4.My problem is, I don't understand where I should put the Symfony project.My OS is Ubuntu 14.04 | How to run symfony via docker-composer |
According to NGINX source codesrc/http/ngx_http.c:if (value[i].len == 1 && value[i].data[0] == '*') {No, you can't | We have an application, serving json with media type:application/vnd.example.v1.0+jsonandapplication/vnd.example.v2.0+jsonand so on.If we want to use nginx'shttp://nginx.org/en/docs/http/ngx_http_ssi_module.html#ssi_typesandhttp://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_types. Do we have to append every possible version number or is there something like a wildcard?Instead of:gzip_types "application/vnd.example.v1.0+json" "application/vnd.example.v2.0+json" "application/vnd.example.v3.0+json"is something likegzip_types "application/vnd.example*+json"possible? | Using gzip_types/ssi_types in NGINX with "wildcard" media types |
Don't use django to deliver static content, specially not when it's static content that's as large as this. Nginx is ideal for delivering them. All you need to do is to create a mapping such as this in your nginx configuration file:location /static/ {
try_files $uri =404 ;
root /var/www/myapp/;
gzip on;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;}With/var/www/myapp/being the top level folder for your django app. Inside that you will have a folder namedstatic/into which you need to collect all your static files with the django manage.py 's collectstatic command.Of course you are free to rename these folders anyway you like and to use a different file structure all together. More about how to configure nginx for static content at this link:http://nginx.org/en/docs/beginners_guide.html#static | I'm having some problems to serve large file downloads/uploads (3gb+).As I'm using Django I guess that the problem to serve the file can become from Django or NGinx.In my NGinx enabled site I haveserver {
...
client_max_body_size 4G;
...
}And at django I'm serving the files in chunk sizes:def return_file(path):
filename = os.path.basename(path)
chunk_size = 8192
response = StreamingHttpResponse(FileWrapper(open(path), chunk_size), content_type=mimetypes.guess_type(path)[0])
response['Content-Length'] = os.path.getsize(path)
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
return responseThis method allowed me to pass from downloads of 600Mb~ to 2.6Gb, but it seems that the downloads are getting truncated at 2.6Gb. I traced the error:2015/09/04 11:31:30 [error] 831#0: *553 upstream prematurely closed connection while reading upstream, client: 127.0.0.1, server: localhost, request: "GET /chat/download/photorec.zip/ HTTP/1.1", upstream: "http://unix:/web/rsmweb/run/gunicorn.sock:/chat/download/photorec.zip/", host: "localhost", referrer: "http://localhost/chat/2/"After reading some posts I added the following to my NGinx conf:proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_redirect off;But I got the same error with an*1instead of a*553*I also thought that It could be a Django database Timeout, so I added:DATABASE_OPTIONS = {
'connect_timeout': 14400,
}But it is not working either. (the download over the development server takes about 30 seconds)PS: Some one already pointed me that the problem is Django, but I haven't been able to figure out why. Django is not printing or loggin any error!Thanks for any help! | NGinx & Django, serving large files (3gb+) |
This actually depends on the filesystem being used. This is probably referring to the stat.blksize filesystem attribute.From thestat(2)manual page:struct stat {
/* ... */
blksize_t st_blksize; /* blocksize for filesystem I/O */The -f option to thestat(1)appears to display this information, and on my Linux box, it shows 4096 as the block size. | From the nginx config file readme:access_log:An optional third parameter indicates the size of the bufferIf write buffering is used, this size cannot exceed the size of the atomic disk write for that filesystem. | What's the "atomic disk write" for a Linux filesystem? |
I'm pretty sure you can't do this out-of-the-box with nginx. This feature is really designed for accelerating file downloads, so it's pretty focused on GET requests.That said, youmightbe able to do something fancy with the lua module. After you've compiled a version of nginx that includes the module, something like thismightwork.Ruby code:def proxy_video(path)
self.status = 200
response.headers["X-Accel-Redirect"] = "/proxy/#{path}"
response.headers["X-Accel-Post-Body"] = "var1=val1&var2=val2"
render text: 'ok'
endNginx config:location ~* ^/proxy/(.*?)/(.*) {
internal;
resolver 127.0.0.1;
# Compose download url
set $download_host $1;
set $download_url http://$download_host/$2;
rewrite_by_lua '
ngx.req.set_method(ngx.HTTP_POST)
ngx.req.set_body_data(ngx.header["X-Accel-Post-Body"])
';
# Set download request headers
proxy_set_header Host $download_host;
# Do not touch local disks when proxying content to clients
proxy_max_temp_file_size 0;
# Stream the file back send to the browser
proxy_pass $download_url?$args;
} | I'm using rails 4 and I'm proxying a GET request to another server like this:def proxy_video(path)
self.status = 200
response.headers["X-Accel-Redirect"] = "/proxy/#{path}"
render text: 'ok'
endIn my nginx config, I have this:location ~* ^/proxy/(.*?)/(.*) {
internal;
resolver 127.0.0.1;
# Compose download url
set $download_host $1;
set $download_url http://$download_host/$2;
# Set download request headers
proxy_set_header Host $download_host;
# Do not touch local disks when proxying content to clients
proxy_max_temp_file_size 0;
# Stream the file back send to the browser
proxy_pass $download_url?$args;
}This works fine for proxying GET requests like:proxy_image('http://10.10.0.7:80/download?path=/20140407_120500_to_120559.mp4')However, I want to proxy a request that passes a list of files that will not fit in a GET request. So I need to pass what currently goes in $args as POST data.How would I proxy this POST data? - Do I need to do something like response.method = :post or something? - Where would I provide the parameters of what I'm POSTing? | Creating a POST request with X-Accel-Redirect with Rails? |
Turns out that the server should be running on 0.0.0.0 if it needs to be reachable by addressing the IP of the instance.So to solve my problem, I stopped the server running resque on 127.0.0.1:3000 and restarted it to bind to 0.0.0.0:3000. Rest everything remains the same as above and it works. Thanks.For reference :Curl amazon EC2 instance | I have two Amazon EC2 instances. Let me call them X and Y. I have nginx installed on both of them. Y hasresquerunning on port3000. Only X has a public IP and domain example.com. Suppose private IP of Y is15.0.0.10What I want is that all the requests come to X. And only if the request url matches the pattern/resque, then it should be handled by Y atlocalhost:3000/overview, which is the resque web interface. It seems like this can be done using proxy_pass in nginx config.So, In nginx.conf, I have added the following :location /resque {
real_ip_header X-Forwarded-For;
set_real_ip_from 0.0.0.0/0;
allow all;
proxy_pass http://15.0.0.10:3000/overview;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}But now, when I visithttp://example.com/resquefrom my web browser, it shows502 Bad Gateway.In/var/log/nginx/error.logon X,2014/02/27 10:27:16 [error] 12559#0: *2588 connect() failed (111: Connection
refused) while connecting to upstream, client: 123.201.181.82, server: _,
request: "GET /resque HTTP/1.1", upstream: "http://15.0.0.10:3000/overview",
host: "example.com"Any suggestions on what could be wrong and how to fix this ? | proxy_pass in nginx to private IP of EC2 instance |
My bet is that the 5MB file is too large for Apache'smax_request_bodysetting (or whatever its name was), leading to the PHP script not being executed, thus never getting to send those headers, which in turns generates the misleading cross domain error.If this assumption is true, you should be seeing more details in your browser's "Net" tab - the upload script should be returning an error condition of some sort.To debug, you could do a normal form-based file upload, test that, and adjust things until it works. | So the point is I have a subdomain which is API endpoint for uploading files. But when I'm trying to upload anything with jQuery to this subdomain (from main www domain) I'm getting errorXMLHttpRequest cannot loadhttp://1.storage.site.net/upload. Originhttp://www.site.netis not allowed by Access-Control-Allow-Origin.I tried everything: headers in nginx, headers in source code, I even tried sending file to stub file with just 123]);In two words: NOTHING WORKS.BUT. I noticed that small files (~1MB) upload correctly and files a little bit larger (say 5MB) — NOT (origin not allowed).Is there any way of solving that? | Cross-domain jQuery AJAX file upload |
A CGI application is simply a standard executable or script - each HTTP request to the web server corresponds to a single execution / instance of that executable or script where environment variables are used to pass information about the request (such as the request URL and request method) and the HTTP request body is passed on the standard input. The script / executable the passes the rawHTTP outputthrough the standard output stream to the web server.For a example of a CGI application see thewikipedia pagefor an example perl script and for more detail have a read through of theCGI specificationFast CGI is an attempt to reduce the overhead of the CGI interface - as starting a new process is a relatively expensive task on many operating systems, Fast CGI attempts to reduce this by allowing a single long-running Fast CGI process to handle many HTTP requests.Although many parts of Fast CGI are similar to CGI (for example the format of the environment variables), with Fast CGIallinformation is passed through the standard input stream.You should try looking at theFast CGI websitefor more information - in particular the Fast CGI specification is on there and explains all of this in detail. | I want to understand how the webserver (for example: nginx) and cgi/fastcgi communicate with each other. How does the webserver pass cgi script to cgi process and how does the cgi process respond to the request.In Nginx, we configure like this to let nginx passes PHP scripts to php-fpmlocation / {
root /home/service/public_html;
fastcgi_pass unix:/tmp/php-fpm-test.socket;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /home/service/public_html/index.php;
include fastcgi_params;
}How does it works?Edit:It would be appreciated if someone could give me a piece of pseudo code to describe the communication between a process (or whatever) and php-fpm unix socket. | How do webserver and cgi process communicate with each other? |
In case anyone was looking for asolutionto the problem itself:The fieldcurrent_saltis no longer the name of the field where the result is stored and needs to be updated.Instead, the field name isoutput, as defined in/usr/include/crypt.hon such a system:/* Memory area used by crypt_r. */
struct crypt_data
{
/* crypt_r writes the hashed password to this field of its 'data'
argument. crypt_rn and crypt_ra do the same, treating the
untyped data area they are supplied with as this struct. */
char output[CRYPT_OUTPUT_SIZE]; | I am trying to compile nginx on Ubuntu machine with GCC. My Glibc version is 2.31.m@feynman:~/Junk/nginx-1.9.9
$ /lib/x86_64-linux-gnu/libc.so.6 --version
GNU C Library (Ubuntu GLIBC 2.31-0ubuntu9.2) stable release version 2.31.I have downloaded a bunch of different versions fromhttps://nginx.org/download/and tried with them and fails every time../configure --with-threads --with-http_ssl_module --with-cc-opt="-Wno-error"
make./configure generates following file inobjs/Makefile:CC = cc
CFLAGS = -pipe -O -W -Wall -Wpointer-arith -Wno-unused -Werror -g -Wno-error
CPP = cc -E
LINK = $(CC)
...This gives me this error below.cc -c -pipe -O -W -Wall -Wpointer-arith -Wno-unused -Werror -g -Wno-error -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs \
-o objs/src/os/unix/ngx_posix_init.o \
src/os/unix/ngx_posix_init.c
cc -c -pipe -O -W -Wall -Wpointer-arith -Wno-unused -Werror -g -Wno-error -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs \
-o objs/src/os/unix/ngx_user.o \
src/os/unix/ngx_user.c
src/os/unix/ngx_user.c: In function ‘ngx_libc_crypt’:
src/os/unix/ngx_user.c:36:7: error: ‘struct crypt_data’ has no member named ‘current_salt’
36 | cd.current_salt[0] = ~salt[0];
| ^
make[1]: *** [objs/Makefile:749: objs/src/os/unix/ngx_user.o] Error 1
make[1]: Leaving directory '/home/m/Junk/nginx-1.9.9'
make: *** [Makefile:8: build] Error 2I tried installing SSL lib and others like that and thought it would help and nothing worked.sudo apt install libpcre3-dev libssl-dev | Compilation of nginx fails due to struct 'crypt_data' has no member named 'current_salt' |
Looks like Nginx doesn’t think it’s talking HTTP/2 as the go client is sending the connection preface message ("PRI * HTTP/2.0") which Nginx thinks is a real message.The likely issue is that Nginx has not stated in the SSL/TLS handshake that it supports HTTP/2 via ALPN (or the older NPN). Which version of OpenSSL (or equivalent) was Nginx built with? Runnginx -Vto see this. Ideally you want 1.0.2 or above to support ALPN.Also check that your SSL/TLS cipher is not usingone of the ciphers forbidden for HTTP/2. Config like below (generated by the Mozilla SSL config generator) should ensure the right ciphers are preferred:# modern configuration. tweak to your needs.
ssl_protocols TLSv1.2;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
ssl_prefer_server_ciphers on; | I'm implementing a http/2 proxy myself, and I'm using Nginx as load balancer.When I use Nginx as h2c load balancer, it works:server {
listen 8443 http2;
location / {
error_log /Users/jiajun/nginx_error_log.log debug;
grpc_pass grpc://127.0.0.1:2017;
}
}Run it:$ go run example/grpc_client/main.go
calling to 127.0.0.1:2019
2019/01/28 11:50:46 gonna call c.SayHello...
2019/01/28 11:50:46 Greeting: Hello worldAnd Nginx access log is:127.0.0.1 - - [28/Jan/2019:11:50:46 +0800] "POST /helloworld.Greeter/SayHello HTTP/2.0" 200 18 "-" "grpc-go/1.16.0" "-"But it does not work while I'm serving it under SSL:server {
listen 8443 ssl http2;
ssl_certificate /Users/jiajun/127.0.0.1.crt;
ssl_certificate_key /Users/jiajun/127.0.0.1.key;
location / {
error_log /Users/jiajun/nginx_error_log.log debug;
grpc_pass grpc://127.0.0.1:2017;
}
}Run it:$ go run example/grpc_client/main.go
calling to 127.0.0.1:2019
2019/01/28 11:53:06 gonna call c.SayHello...
2019/01/28 11:53:06 could not greet: rpc error: code = Unavailable desc = transport is closing
exit status 1And, Nginx access log is:127.0.0.1 - - [28/Jan/2019:11:53:06 +0800] "PRI * HTTP/2.0" 400 157 "-" "-" "-"So I'm trying to find out why it return a 400 while I'm using SSL. But Nginx does not record the process in error log even I've set log level to debug(and it had compiled with--with-debugoption).Is there any good idea to debug it? | How to find out why Nginx return 400 while use it as http/2 load balancer? |
Ok for staters Nginx has nothing to do with this question it's that is quite clearly PHP sending and receiving data.It is more than likely your remote system is not closing the socket at the correct time or is just taking far to long to respond.while (($chunk = socket_read($this->socket, 2048, PHP_BINARY_READ)) !== FALSE)
{
$response .= $chunk;
if (substr($chunk, -1) == chr(27))
break;
}This code block has the potential to be an infinite loop with this code if the remote system has not closed the connection/socket and told you about it will keep trying to read and be waiting for 2048 (Bit's or Bytes - I can never remember which size it asks for sure a comment will inform) of data to come through or the socket to close before the read is finished.So a couple of things to try to lower your read bytes set it to something like128, put in a timer to your socket (requires async programming in PHP) read so kill it after 28 seconds give your code 2 more seconds to execute (safely exit). or useset_time_limitto increase your time limit.If you do increase your time limit you will need to increase the amount of time nginx is allowed to get the response from the connection to PHP to do this set yourfastcgi_read_timeout | My application is listening on a unix domain socket (UDS) for incoming data while nginx is sending data using PHP. Sending smaller data chunks of several KB works perfectly but as soon as it gets to certain limit, the browser gets the error504 Gateway Time-out, nginx logsupstream timed out (110: Connection timed out) while reading response
header from upstream, client: 127.0.0.1, server: _, request: "GET
/foo/bar.php HTTP/1.1", upstream:
"fastcgi://unix:/run/php/php7.0-fpm.sock", host: "localhost"The socket still gets some data (always cut at around 1.5 MB) and replies but the webserver doesn't seem to get the response.
Are there any UDS stream limits or nginx variables that must be adjusted?PHP code:public function send ($msg)
{
$str = "{$msg}".chr(27);
$ret = socket_write($this->socket, $str, strlen($str));
if ($ret == FALSE)
{
return false;
}
else
{
$response = "";
while (($chunk = socket_read($this->socket, 2048, PHP_BINARY_READ)) !== FALSE)
{
$response .= $chunk;
if (substr($chunk, -1) == chr(27))
break;
}
//close the connection
if ($this->connected !== false)
{
socket_shutdown($this->socket);
socket_close($this->socket);
$this->connected = false;
}
return $response;
}
} | ngnix transfers data to a unix domain socket incompletely |
There are a few things here. To start, I don't think you're going to see much gain with running different types of requests in different processes. Your disconnect handlers are probably going to be very light - not doing much besides cleanup. Connect might not do much either and receive will get most of the load.You're betting off using the --threads parameter and starting multiple threads. Your current setup would only run one thread for each type of handler.The way runworker works is that it communicates with Daphne over your channel layer (ex Redis). All of the workers are listening to a queue. When a request comes in one worker will process it. While that worker is processing the request the other workers will wait for subsequent requests and process them. Once they send their response they go back to listening to the queue. If there are no --only-channels specified, each process will be pulling off requests and working on them as fast as it can and none of them will be waiting around.Its up to you to find the best balance of threads/workers by running multiple processes and the --threads parameter. You can also have workers reserved for heavy channels so they don't bring down your site.Having multiple Daphne instances will help. But since all they do is send messages between your server and the workers you might not see the benefit of running 4 of them.Everything stated here is not appliacable to Channels 2. This is for the old version of Django Channels. | I am usingdjango-channelsto addHTTP2&WebSocketsupport for my application. I could not find a lot of documentation as to how to scale channels. Below is mynginxconfiguration that load balances multiple instances ofdaphnerunning on the same machine but different ports. Is this the correct way to do it?upstream socket {
least_conn;
server 127.0.0.1:9000;
server 127.0.0.1:9001;
server 127.0.0.1:9002;
server 127.0.0.1:9003;
}
server {
listen 80;
server_name 127.0.0.1;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/niscp/home-screen;
}
location /nicons/ {
root /home/niscp/home-screen;
}
location / {
include uwsgi_params;
uwsgi_pass unix:/home/niscp/home-screen/home-screen.sock;
}
location /ws/ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://socket;
}
}Along with that, I am running individual instances ofworkersto listen to individual channels in the following manner:python manage.py runworker --only-channels=websocket.connect
python manage.py runworker --only-channels=websocket.receive
python manage.py runworker --only-channels=websocket.disconnectI have gotuwsgito handle all http requests the waydjangonormally handles them. Alldaphneandworkersdo is handleWebSocketrequests.
Is this a viable method to scaledjango-channels, or is there something I could do better? | Running multiple instances of daphne behind a load balancer: django-channels |
It seems there was one thing I missed when I changed the settings - stopping to listen for breakpoints and then trying again. This seems to have fixed the issue... | I figured I'd try using nginx instead of Apache and see how that works, and I'm up and running, but I cannot for the sake of my life figure out how to make PhpStorm capture the incoming xdebug connection. It worked perfectly when I was running Apache.Usually, you'd get an "incoming connection"-window in PhpStorm - this window now shines with its absence - and yes; I've read every single PhpStorm / Xdebug question on StackOverflow and neither has solved my issue.Configuration:
OS: OSX Mavericks
PhpStorm version: 7.1
Xdebug version: 2.2.5Note that I'm running nginx and PHP throughphp-fpmwhich is working as expected. I've pointed out the same PHP-file as php-fpm is running to PhpStorm which successfully finds Xdebug as the debugger.Sincephp-fpmis running port 9000 just as Xdebug, I've changed this to 9900 and 9001 (tried both) and made sure to check myphpinfo()to see that the server has updated the php.ini config with it and I've checked that I've updated the Xdebug port in PhpStorm. I've also enabled "Start listening for debug connections" in PhpStorm.Xdebug config from php.ini:[xdebug]
zend_extension = /usr/local/Cellar/php55/5.5.14/lib/php/extensions/no-debug-non-zts-20121212/xdebug.so
xdebug.auto_trace=0
xdebug.default_enable=1
xdebug.idekey="PHPSTORM"
xdebug.profiler_enable=0
xdebug.profiler_enable_trigger=0
xdebug.profiler_output_dir="/tmp"
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_mode=req
xdebug.remote_port=9001As mentioned - xdebug is loaded when I loadphpinfo()in the browser and I've set the correct port in PhpStorm.Thanks for your help. | No incoming connection for PhpStorm with xdebug (nginx / php-fpm) |
This problem is indeed due to a bug inWerkzeug. As you noticed, this is now corrected since Jun 4, 2013 (cf. therelated commiton Github). You can have a bug free version of Werkzeug by using the version0.9.5instead of the0.9.4.Moreover, to troubleshoot your problem, I addedapp.debug = Truejust after the initialization of your Flask application. This allows me to got the following error in uWSGI logs:Traceback (most recent call last):
File "/home/afigura/.virtualenvs/stack-python2/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/home/afigura/.virtualenvs/stack-python2/lib/python2.7/site-packages/flask/app.py", line 1821, in wsgi_app
return response(environ, start_response)
File "/home/afigura/.virtualenvs/stack-python2/lib/python2.7/site-packages/werkzeug/wrappers.py", line 1201, in __call__
start_response(status, headers)
TypeError: http header key must be a stringThis corresponds to the error mentioned inthe bug you foundon Github.So, you can use the following workaround to getFlask/Werkzeugworking withunicode_literals:response.headers = {b'WWW-Authenticate': 'Basic realm="test"'}Or:response.headers = {str('WWW-Authenticate'): 'Basic realm="test"'}But I recommend to simply update your Werkzeug version to >=0.9.5 if you can.Also, please note that although theheadersattribute of a Flask/Werkzeug response behaves like a dictionary, it is in fact aHeadersobject (seeWerkzeug source code). Hence, I advise you to use it as follows:response.headers['WWW-Authenticate'] = 'Basic realm="test"'You can see some examples about this on theFlask documentationof the functionmake_response. | Adding headers with unicode_literals enabled seems to fail with Nginx, uWSGI and a simple Flask app:# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from flask import Flask, make_response
app = Flask('test')
@app.route('/')
def index():
response = make_response()
response.status_code = 401
response.headers = {'WWW-Authenticate': 'Basic realm="test"'} # Fail
# response.headers = {b'WWW-Authenticate': b'Basic realm="test"'} # Succeed
return response
if __name__ == '__main__':
app.run(debug=True)The app is available directly for debug purpose or through Nginx -> uWSGI -> Flask and works well.When I use a browser to connect directly to the app, I've got a login dialog and theWWW-Authenticateheader is correct.The same request going through Nginx returns a headerTransfert-Encoding: chunkedand
discard theWWW-Authenticateheader.Forcing bytestring (b'...') format to add the header make the app works as expected in both cases.
The file is encoded in UTF-8 and there's acoding` declaration for the Python interpreter.
We're using Python 2.7.3, Nginx 1.4.2 and uWSGI 1.3.Is there any known incompatibility between Nginx or uWSGI, Flask and unicode_literals?
Thanks!edit:
The problem seems to come from uWSGI (https://github.com/unbit/uwsgi/blob/master/plugins/python/wsgi_headers.c#L116), since it only checks for PyString and not PyUnicode for Python2, if I understand this code correctly.edit:
Armin Ronacher has fixed a similar bug (https://github.com/mitsuhiko/flask/issues/758) 5 months ago, but I didn't find the commit in werkzeug git log yet. I don't know if the fix is scoped to theredirect()function or more broadly on headers handling. I'm using Werkzeug 0.9.4 and Flask 0.10.1. | Add headers in a Flask app with unicode_literals |
301 redirect is exactly what nginx shall do with that rewrite rule: because you put $scheme://$subdub at the replacement part, nginx will do a 301, ignoring that "break" flag.If the replacement string begins with http:// then the client will be redirected, and any further rewrite directives are terminated.Are you trying to "rewrite" or "redirect"? If it's just for rewrite, you can remove that rewrite directive:rewrite ^ $scheme://$subdub break;and it will work because your upstream server could rely on the HOST header to determine the traffic target (virtual hosting).Alsoyour host header sent to the upstream server is wrong. It should beproxy_set_header Host $subdub;$scheme should not be put in the Host header. | I want to achieve the following:Request Host:http://example.com.proxy.myserver.comShould be rewritten tohttp://example.comand passed to a squid server via nginx proxypass.server {
listen 80;
server_name ~^(?.*)\.proxy\.myserver\.com$;
location / {
rewrite ^ $scheme://$subdub break;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $scheme://$subdub;
proxy_set_header Request-URI $scheme://$subdub;
proxy_pass http://localhost:3128;
proxy_redirect off;
}
}The problem is, that nginx redirects this request immediately tohttp://example.comAny ideas how to get this working? | Rewrite nginx host and proxypass to squid |
So, you probably won't be able to use Node.js on a typical 'hosted server'. These servers are typically running Apache and only support a limited set of languages. There are several providers that offer Node.JS hosting, including the creators: Joyent.Otherwise, you'll need control of the actual server so that you can run thenode myapp.jscommand. For a list of possible providers, seehere.Once you get the app runningnode myapp.js, it should start handling incoming web requests, just like any other web server. Now, if someone is using nginx, they're probably using it as a load-balancer or to serve static content.If you don't understand how or why it's configured this way, you definitely need to talk to the project owners. The rest of the details depend completely on where / how you're hosting and the answers to the nginx questions. | Ive been given the task of localising a facebook app that is built in Node.js that am told uses Nginx for SSL.This is my first foray into the world of Node.js and I have hit a wall in understanding the deployment process involved in pushing an node app to the world wide web (in order to access it through facebook).I have a background in front-end development with javascript, AJAX, html and css. As well as backend PHP, and MYSQL. The task of localising the content I'm not worried about as it is only a matter of swapping out a couple of images. Its my core understanding of how the node.js puzzle fits together where it falls down. Not to metion how Nginx even fits in.I have done alot of searching online and found a lot of beginners tutorials eghttp://www.nodebeginner.org/which is fine but doesn't touch on how node web apps are deployed. I can build the simple hello world example locally but how does this become a "proper www.website". There are also a tonne of other resources out there but they presume a more advanced level of understanding and technical know-how. I just need it in layman's terms.I get that Node.js is server-side javascript so this obviously means it lives on a server right? i currently have a domain, website and hosting plan can i use this server? i access it through a cpanel or ftp. Or do i have to create a new server from scratch? Maybe a virtual server maybe usinghttps://www.virtualbox.org/what would be this involve?any help you guy may be able to give me is much appreciated.cheers | node.js deployment questions |
You are right about HttpRedis being more geared towards caching. You would be better served using the redis2 module. The commands you need to execute are better provided by the more general case that redis2 provides | I want to maintain a dynamic database in Redis with SEO-friendly URLs as keys and nasty querystring URLs as values. I want to call this directly from Nginx when the request comes in, get the nasty querystring URL and pass that along to Apache to serve content.I have thought about just having a flat map file, but that would be pretty huge (200,000+ entries) and it would have to be updated often by a cron job or something... not very elegant.My idea is something like this:map $uri $new {
# instead of this...
# include /path/to/the/nginx_map.txt;
# I want to do this...
redis_magic_thing GET $uri;
}I have been checking out the HttpRedis Module for Nginx but the examples are really sparse and it seems more geared towards serving up cached content. I have also checked out theRedis2module, but that seems like overkill. I just need to do plain old GET commands.Can I use the HttpRedis module to do this and hook right into Redis? If so, what would such a configuration look like?Thanks in advance for your help. | Use Redis to serve URL map to nginx |
Your code isFull NETand not evenNET Coreand trying to deploy it toMono Framework. This may not work, Convert your project intoMonoorNET Coreand retry. | Here is my current setup:My Local Computer: This is where I created and programmed my ASP.Net WebForms project with Cloudflare Flexible SSL enabled using visual studio 2015 professional on Windows 10. I also have the team explorer enabled meaning my project is synced to Github and all of my files are also stored there in my own repository.My Server Computer: Running Fedora 24, I've installedthe dotnet CLI (a.k.a .Net Core),apache (httpd), nginx, andMono for ASP.Net. I want to deploy/publish and host my webforms project on this computer in the default web directory (/var/www/html/mysite/)The problem is, the dotnet cli relies on aproject.jsonandis not compatible with WebForms. .Net Core is basicallynot an option. When I use mod_mono, I get anError 500(see below) if I connect tohttps://localhost:9000/while running the server using the commandxsp4 --port 9000. I can't usexsp4 --port 80orxsp4 --port 443because then it claimsAddress is already in useeven thoughhttpdis the only process listening on those ports.Note that I can sucessfully build the project using thexbuildcommand.How can I take my project from github or my local computer and deploy it on to my server computer? Am I missing something? Here is my virtual hosts configuration for reference:httpd.conf.I typically get no errors when starting httpd.service.EDIT:I've also usednginxwithfastcgi-mono-server4withthisconfiguration instead with nginx, which I got straight fromhere, but still no luck. I usually get thisError 500:other times I can get other types ofError 500. If there is a solution that works with either apache or nginx, please let me know. | Deploying ASP.Net Web Forms project to Fedora 24 |
Easy way is try to reload your dropletsudo shutdown -r now | I am trying to launch an app withgunicornandnginxand have had to double back to delete and change files a few times. This time, I ran into issues.I first created an upstart file...sudo nano /etc/init/gunicorn.confdescription "Gunicorn application server handling flowershop"
start on runlevel [2345]
stop on runlevel [!2345]
respawn
setuid ubuntu
setgid www-data
chdir /home/ubuntu/flowershop
exec env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/flowershop/flowershop.sock flowershop.wsgi:applicationThen I ran...sudo service gunicorn startand it started!I had to change the name of the socket it created, so I deleted the/etc/init/gunicorn.confupstart file, created a new upstart file with the same name as the last and attempted to runsudo service gunicorn start.It now returns the following error messages that correspond the the following commands...sudo service gunicorn start
start: Job failed to start&&sudo service gunicorn stop
stop: Unknown instance:This clearly had to do with my meddling, but I don't have the slightest clue how to fix it. | Gunicorn Upstart File Not Starting |
We use elastic beanstalk with multiple docker containers(allows you custom nginx version) with following1.Nginx configlocation /ws/
{
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://unix:/<>;
}Enable TCP mode load balancing in elastic load balancer if you are using one. | I deploy a nodejs application on the aws beanstalk servers and want to use socket.io feature based on WebSocket protocol. I know there's a discussionhereto directly connect to nodejs servers instead of using nginx as an proxy server. But if I still want to have the nginx as proxy server because of extra features provide by nginx, such as static files, ...etc.I find it's already supportWebSocket proxyingon nginx 1.3.13 and I found it seems aws elastic-beanstalk still use the 1.2.x nginx.So I am wondering if there's any way to upgrade nginx version under beanstalk and how to enable WebSocket proxying to nodejs server.Thanks | how to enable WebSocket with nginx on AWS Elastic Beanstalk server? |
Will add another step to my pre-commit script to replace all direct links with links to versioned files in the minimized CSS.Seems there is no better way to do it. If you think of any, let me know and I'll consider marking that one as accepted answer.Thanks for your comments! | I am setting far-future expires headers for my CSS/Javascript so that the browsers don't ever ask for the files again once they get cached. I also have a simple versioning mechanism so that if the files change, the clients will know.Basically I have a template tag and I do something likewhich will become.The template tag opens a filejavascript/c/c.js.vwhere it finds the version number and appends it to the query string. The version is generated by a shell script (run manually for now, will probably add pre-commit hook) which checks whether the file has changed (usinggit diff).This is all working fine, EXCEPT:I want to implement the same kind of versioning for images as well. But images can be referenced from CSS - which is a static file (served by nginx) - so no template tag there.What is a better approach for file versioning?Alternatively, I am thinking about replacing the template tag with a middleware which changes all links before returning the response. That is better than the template tag, which can be mistakenly omitted. But still doesn't solve the issue of images referenced from CSS.Also, I'm aware that having the version as part of the query string might cause trouble with certain proxies not caching the file - so I consider making the version part of the filename - for examplejavascript/c/c.123456.js.Note: It looks like there is no way to solve this issue using Django (obviously - since I don't even serve the CSS through Django). But there has to be a solution, perhaps involving some nginx tricks. | Static file versioning with Django |
Found my own answer... Here is is:Basically nginx configuration needed redirect urls to /index.html (not to my bundle.js, of course)The addition oftry_filesin nginx conf takes care of that:location / {
root /var/www;
index index.html;
try_files $uri $uri/ /index.html;
}Additionally I modified the router's main rednering:ReactDOM.render(
(
)
, document.getElementById('navbar'));And in AppMainNewNav render() I modified the navigation to something like this:
Videos
About
| I have a working web app served by nginx with cherrypy in the backend and ReactJS for the front-end.The app grew so I want to use react-router to provide quick access to pages with URLs.
For example I want that my.domain.name/user will get the part in my app that manages user.My single index.html includes the js bundle like this:Until now my app started by rendering AppMain.
Now, I created a NoMatch class and I've put both into a react-router, like this:ReactDOM.render((
), document.getElementById('main-central'));When trying this it worked nicely. Usinghttp://my.domain.namegave me the app as before.
But thoeritcally now tryinghttp://my.domain.name/whatevershould have renderred whatever NoMatch is rendering. But instead I get the nginx 404 page.So I believe an nginx-side configuration is needed but maybe not only (which is why I brought the entire story above).Nginx configuration (http part) looks like this:upstream app_servers {
server 127.0.0.1:9988;
}
# Configuration for Nginx
server {
location / {
root /var/www;
index index.html;
}
# Proxy connections to the application servers
# app_servers
location /api {
proxy_pass http://app_servers/api;
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-Host $server_name;
}
}As you can see cherrypy is getting all /api/* paths.I have static content under /css, /img etc that I want to be served properly.So I need everything not static and not /api to go to js/bundle.jsHow do I configure that in nginx?
Do I need to do something in cherrypy or javascript differently?Thanks in advance. | How can I configure react-router to with nginx/cherrypy and my current reactjs app |
Use(?i)to match case-insensitively -http://perldoc.perl.org/perlretut.htmlLocation block is not necessary. Try this.rewrite (?i)^/WapsiteDataFetch(.*) http://images.xample.com/xyz/images$1 permanent; | Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Closed10 years ago.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.Improve this questionI want to do case insensitive URL redirection innginx.
Below is my code.location ~* WapsiteDataFetch{
rewrite WapsiteDataFetch(.*) http://images.xample.com/xyz/images$1 permanent;
}In the above case,www.example.com/WapsiteDataFetchis redirected properly tohttp://images.xample.com/xyz/images.
However, the URL"www.example.com/WAPSITEDATAFETCH"is not redirected properly.Even if Ichangea single character, it is giving a 404 error.I have tried many blog posts and have seen many post from Stack Overflow and many of them have suggested "~*", but in my case it was not helping me.How can I fix this? | nginx case insensitive URL redirection [closed] |
Normally that means it's still running, but that should only happen if it's in daemon mode. After you started it, do you get a command prompt, or do you have to stop it with Ctrl-C?If you get a command prompt back it's deamon mode and you have to stop it withpaster server development.ini stopIf you have stopped it with Ctrl-C (and not Ctrl-Z of course), I have no idea. | I'm running pylons and I did this:
paster server development.ini
It's running on :5000But when I try to run the command again:
paster serve development.iniI get this message:
socket.error: [Errno 98] Address already in useAny ideas? | Pylons: address already in use when trying to serve |
The problem with your node benchmark is that you store the static file in a variable inside the V8 heap. Due to the way how V8 handles memory it can't directly send data contained in javascript variables to the network, because addresses of allocated objects may change during runtime, therefore V8 has to make a copy of your 1.8MB string on every request, sure that kills performance.What you could do is to use aBuffer:replace:longAssString = fs.readFileSync(pathToABigFile, 'utf8');with:longAssString = fs.readFileSync(pathToABigFile);that way you have your static file in a buffer, buffers are stored outside of V8s heap and require no copy when sent to the network and should therefore be much faster. | Take the same code that sits on nodejs.org home page. Serve a static file that is 1.8Mb. And do the same with Nginx, and watch the difference.Code :http://pastie.org/3730760Screencast :http://screencast.com/t/Or44Xie11FnpPlease share if you know anything that'd prevent this from happening, so we don't need to deploy nginx servers and complicate our lives.ps1. this test is done with node 0.6.12. out of curiosity, i downgraded to 0.4.12 just to check if it's a regression, on the contrary, it was worse. same file used 25% twice.ps2. this post is not a nodejs hate - we use nodejs, and we love it, except this glitch which actually delayed our launch (made us really sad), and seemed quite serious to me. i've never read, heard, seen or expected to come across. | Why Nodejs serves a file with 80x more CPU usage than Nginx? |
That's correct, as nginx will be the remote host. You need to specify a custom log format to log theX-Forwarded-Forheader, see theconnect logger documentation.app.use(express.logger(':req[X-Forwarded-For] - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"')); | I'm using NODE.js behind NGINX server, this is my Nginx configuration:upstream example.it {
server 127.0.0.1:8000;
}
server {
server_name www.example.it;
location / {
proxy_pass http://example.it;
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;
}
}All works good, the requests are correctly sent from nginx to node BUT I saw a problem in the log file generated from Express.js.The problem is thatALL THE REQUESTSare saved as done from 127.0.0.1, why?I don't seen any remove hosts (the real ip of who made the request).Thanks | NGINX as proxy of Node.js |
Try (re)installing the native apache module (after installing the gem)apt-get install libapache2-mod-passengerI think I had the same problem and it worked after that.Good luck! | Running in a Linode slice with Ubuntu 10.04 LTS. I am getting a 500 Internal Server Error.The Apache log has:Apache/2.2.14 (Ubuntu) Phusion_Passenger/2.2.7 configured -- resuming normal operationscaught SIGTERM, shutting down*Passenger could not be initialized because of this error: The Passenger spawn server script, '/usr/local/lib/ruby/gems/1.8/gems/passenger-3.0.0/lib/phusion_passenger/passenger-spawn-server', does not exist. Please check whether the 'PassengerRoot' option is specified correctly.But when we run:
sudo passenger-install-apache2-module. Passenger does not complain.On restart we get:
sudo /etc/init.d/apache2 restart
* Restarting web server apache2
[Sat Oct 23 23:58:30 2010] [warn] module passenger_module is already loaded, skipping
... waiting [Sat Oct 23 23:58:31 2010] [warn] module passenger_module is already loaded, skipping
...done.Any ideas?Thanks in advance! | Issue with Passenger - Apache |
CloudFlare allows you to block certain countries from accessing your website at the CloudFlare level. To do so:Select your domain in your CloudFlare Control PanelSelect the "Firewall" tabOn the "IP Firewall" tab, you can enter a IP, IP range, orCountryand click block.This will block the country from all your websites on the CloudFlare level, before any attack even hits your server.If you require to block it with your Nginx solution rather than CloudFlare's firewall for whatever reason, you can look at enabling "IP Geolocation" under the "Network" tab of the Control Panel. This adds the header "HTTP_CF_IPCOUNTRY" to all requests, and will contain the Country Code (I.e US, UK, RU) in the header.If you need to block any requests based off certain IPs, or perform the IP lookup yourself. Then you should use the default CloudFlare header that is included with every request that holds the client's IP named "CF-Connecting-IP".
For future information, CloudFlare has a goodarticlewritten here on how they handle their headers. | Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.Closed7 years ago.Improve this questioni tried to block countries nginx.conf with below codes:geoip_country /usr/share/GeoIP/GeoIP.dat;
map $geoip_country_code $allow_visit {
default yes;
RU no;
}But im using CLoudFLare /cdn service.so when i block some countries.sometimes i cannot login to my system.Coz cloudflare servers maybe in my block countries.So i should remove cloudflare ips from block country list.But how can i do that?
any advice?im using ubuntu 14.04 / nginx on my server..*and now im under the attack.You guys know, theres cyber war so i
should solve this problem fastly.*Thanks in advance. | How to block countries from server when using cloudflare? [closed] |
I can confirm answer 1 addresses the underlying problem (I'm a new SE user so I can't upvote it yet). Here is more detail for search engines:From/var/log/nginx/error.log2014/04/30 08:07:48 [crit] 35135#0: *116437 open() "/var/lib/nginx/proxy/7/09/0000001097" failed (13: Permission denied) while reading upstreamIn my case this happened because I recently changed the user under which nginx runs (the default nginx config useswww-datain/etc/nginx/nginx.conf).My solution was tochown -R correct_user:root /var/lib/nginx/proxy. I imagine I could also haverm -rf'd the existing/var/lib/nginx/proxysubdirectories with the expectation that nginx would recreate them using thecorrect_useras owner.eric-francis thanks for figuring this out! This easily saved me a day of hunting. | I just upgraded my nginx from 1.4.2 (/usr/local) to 1.4.7 (yum) on AWS EC2. I now have a pair of errors occuring on the client side:GET https://subdomain.mysite.com/assets/application.css net::ERR_CONTENT_LENGTH_MISMATCH
GET https://subdomain.mysite.com/assets/application.js net::ERR_CONTENT_LENGTH_MISMATCHI am at a loss for this and google has not been much help. Any ideas on where to start? All help appreciated. Could the switch from a manual install to a yum install be the issue? | application.css and application.js net::ERR_CONTENT_LENGTH_MISMATCH |
To discover your problem, first insettings.pysetALLOWED_HOSTStemporarily to:ALLOWED_HOSTS = '*'And then in somewhere in yourview, try to print out and see output of this command:print(request.META['HTTP_HOST']) # or print(request.get_host())Then according to output, set that (just domain of it as an list) to yourALLOWED_HOSTS.Notes:UseALLOWED_HOSTS = '*'may have security issue for you, read
about thathere.After every change you need to restart your service(apache/nginx). | I'm trying to lunch my app on VPS inDebug=Falsemode.Debug=Trueworks fine but when I change it to false I got this error. I'm using Apache for rendering python pages and Nginx to serve my static files. I tried using this [answer]:Debugging Apache/Django/WSGI Bad Request (400) Errorbut it's not working at least for me. And this is my wsgi config:#wsgi.py
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'example.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
path = '/var/www/example'
if path not in sys.path:
sys.path.append(path)And also I've added below code to my settings file:ALLOWED_HOSTS = [
'.example.com', # Allow domain and subdomains
'.example.com.', # Also allow FQDN and subdomains
] | Django Bad Request(400) Error in Deployment with Apache/NginX |
Create a newserverblock where you set theserver_nameto the desired domain. The normal directory and file structure of nginx looks as follows:/etc/nginx
|
|---- /sites-available
| |
| |---- default.conf
|
|---- /sites-enabled
|
|---- default.conf -> ../sites-available/default.confYou have to create a new file insites-availablewith the newserverblock in it for your sub-domain and create a symbolic link to this new file insites-enabled. A simple reload of nginx will bring your new server up.Your new file structure looks as follows:/etc/nginx
|
|---- /sites-available
| |
| |---- analytix.conf
| |
| |---- default.conf
|
|---- /sites-enabled
|
|---- analytix.conf -> ../sites-available/analytix.conf
|
|---- default.conf -> ../sites-available/default.confHere are the commands involved to do this very fast directly on your server:# cd /etc/nginx/sites-available
# cat default.conf > analytix.conf
# editor analytix.confChange the lineserver_name *.mydomain.com;toserver_name analytix.mydomain.com.# ln -s analytix.conf ../sites-enabled/
# nginx -tOnly continue if it says that your configuration is okay (which it should be).# service nginx restartThat’s it (please note that all of the above commands are meant for a Debian based distro and some commands might differ if you use something else).In order to deliver the contents of a different software on your server you have to change therootdirective in your configuration and point it to the document root of the other software.# editor analytix.confChangeroot /home/ubuntu/virtualenv/mydomain/homelaunch/;toroot /path/to/other/software;and reload your nginx.# nginx -t && service nginx reloadThat’s it, your new application should be serving now. | I've done my prior research, but cannot seem to find how to properly configure nginx to accept a subdomain.I currently have it properly configured for mydomain.com, but not analytix.mydomain.com:server {
listen 80;
server_name *.mydomain.com;
access_log /home/ubuntu/virtualenv/mydomain/error/access.log;
error_log /home/ubuntu/virtualenv/mydomain/error/error.log warn;
connection_pool_size 2048;
fastcgi_buffer_size 4K;
fastcgi_buffers 64 4k;
root /home/ubuntu/virtualenv/mydomain/homelaunch/;
location /static/ {
alias /home/ubuntu/virtualenv/mydomain/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"';
}
}theserver_namedeclaration is accepting.mydomain.comwhich is good.If I accessanalytix.mydomain.com, it throws a Http 500 default which is fine, because its throwing it from the existing application atmydomain.comThe domain is already propogated to this server I'm trying to access it on.How can I designate a folder, at a path, to house the contents foranalytix.mydomain.com? I would assume i would require changing an attribute in the nginx conf (as shown above) | Configure Nginx with a Subdomain |
The gzip has nothing to do with Angular, it's a server thing.
In nginx you can enable it by settinggzip on;Like below:server {
gzip on;
gzip_types text/plain application/xml;
gzip_proxied no-cache no-store private expired auth;
gzip_min_length 1000;
...
}See the article below for more details:https://docs.nginx.com/nginx/admin-guide/web-server/compression/ | does anyone know how to enable gzip text compression in nginx and universal angular? I don't know where to start doing it | How can I enable gzip text compression in universal angular and nginx? |
This has been updated in Dokku and can be done from the CLI:dokku nginx:set node-js-app client-max-body-size 50m.https://dokku.com/docs/networking/proxies/nginx/#specifying-a-custom-client_max_body_size | So I've just pushed my app to Dokku (Digital Ocean) - and get the following error returned from an ajax post:POSThttp://example.com/foo413 (Request Entity Too Large)A quick google shows this problem is due to client_max_body_size being too low. So I've SSH'd into the server, opened up the apps nginx.conf and increased it as per instructions here:client_max_body_size 100M;https://github.com/progrium/dokku/issues/802However, I still have the same problem... Do I need to restart a process or something? I tried restarting the dokku app - but all this did was to overwrite my nginx.conf file. | Dokku (Digital Ocean) client_max_body_size node.js |
Add a space between if and (. that should do the trick! | I try to return 503 status code when the user agent header has a specific value. I tried outside and inside the location block. But when I reload the this config nginx failes to reload:upstream api{
server 127.0.0.1:1336;
}
# the nginx server instance
server {
listen 0.0.0.0:80;
server_name api.project.com;
# if($http_user_agent = "android") {
# return 503;
# }
# pass the request to the node.js server with the correct headers
location / {
# if($http_user_agent = "android") {
# return 503;
# }
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://api/;
proxy_redirect off;
}
}Any ideas whats wrong? I am using nginx/1.4.7From syslog:nginx: [emerg] unknown directive "if($http_user_agent" | Nginx unknown directive "if($http_user_agent" |
Possible error-sources:You use the internal EC2 ip and not the public.You don't have any security policies set and you are hitting the EC2 firewall.iptables is not configured correctly, disable it until it works without.Nginx does not listen on the correct port. Use the default config. | I installed Nginx with phusion passenger, but I am having trouble accessing the server. I am using the default configuration file, yet I never get a response from the server when I try to visit the IP address in my browser. On my server I can do :curl 127.0.0.1To get a response, but visiting the IP address in the browser always times out. I made sure port 80 was open by executingsudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT, but nothing changed. I am using Ubuntu. | Having trouble running nginx on EC2 instance |
Make sure that server1 is not returning compressed content. if its being returned gzipped, nginx won't uncompress it to apply the ssi rules to it.you can ensure the reponse is returned in plain text by clearing the Accept-Encoding header:location /hello-world.html {
ssi on;
proxy_set_header Accept-Encoding "";
proxy_pass http://tom.office.bla.co.uk:8080/hello-world/;
} | I'm trying out nginx. I would like to use it to perform the following:Retrieve a page from a server1 which includes some SSI commandsProcess the SSI commands, eventually including content from server2Return the resultant pageI've got SSI working when using a local file, but not when using the page from a server1 using proxy_pass.Here's my config I'm using to try to achieve the above.events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name localhost;
location /hello-world.html {
ssi on;
proxy_pass http://tom.office.bla.co.uk:8080/hello-world/;
}
}
}For testing purposes, I'm using a simple SSI command, as shown in the output my browser actually ends up with, which is identical to the content on server1:
Do I need to use something other than proxy_pass, or is it just not possible? Thanks! | With nginx, how do I run SSI on a page returned from another server? |
I fixed it. Removed alllocationand addedpassenger_enabled on;outside. | This is my first rails app i am deploying to a server other than heroku.I deployed my rails app to digitalocean successfuly. When i type the ipaddress in browser, home page shows up. But when i try to redirect to other controllers likexxx.xxx.xxx.xx/users/sign_init show404 Not Found. Also none of the images are showing up./etc/nginx/sites-enabled/defaultserver {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name mydomain.com;
passenger_enabled on;
rails_env production;
root /home/deploy/myapp/current/public;
# redirect server error pages to the static page /50x.html
error_page 500 502 503 504 /50x.html;
location = / {
passenger_enabled on; <-added this line for home page to show up
}
location = /users/sign_in {
passenger_enabled on; <-added this line for sign_in view to show up
}
}I dont know what i am missing. do I have to addpassenger_enabled on;to each location?or is there a common configuration for all the uri's of the application? | Nginx - passanger displays 404 not found for rails controllers |
http://nginx.org/en/docs/ngx_core_module.html#error_logindicates that:the default value iserror_log logs/error.log error;that for debug logging to work, nginx needs to be built with --with-debug.`what's happening is that you're falling through to the default value, I'm not spotting any syntax errors so my guess is that your nginx is not compiled with --with-debug.you can check that with thenginx -V(note: that's capital V) | I am currently wanting to use NGINX in my Rails setup. I have placed the configuration files in the directoryRAILS_ROOT/config/nginx. Here is my config-file placed nameddevelopment.confand themime.types-file.I am wanting to place my logs in theRAILS_ROOT/log-directory.This is mydevelopment.conf:worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
# main access log
access_log log/nginx.access.log;
# main error log
error_log log/nginx.error.log debug;
sendfile on;
keepalive_timeout 65;
server {
listen 9001; #omg!
server_name local.woman.dk;
rewrite ^/(.*)/$ /$1 last;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_max_temp_file_size 0;
location / {
ssi on;
proxy_pass http://127.0.0.1:3000;
}
}
}I am starting NGINX from my RAILS_ROOT with this command:nginx -p . -c config/nginx/development.confAnd I get the following error:nginx: [alert] could not open error log file: open() "./logs/error.log" failed (2: No such file or directory)My version is this:[(master)]=> nginx -v
nginx version: nginx/1.2.4Am I doing anything wrong? | Why is NGINX wanting to use ./logs/error.log as default? |
It depends on your default configuration, but fromthis answer on ServerFaultyou must define a default vhost in Nginx, otherwise it will use the first one as a default.Basically, your configuration should look like this in order to allow only requests to "mywebsite.com.br" to pass:server {
listen 80 default_server;
location / {
# or show another site
return 403 "Forbidden";
}
}
server {
listen 80;
server_name mywebsite.com.br;
location / {
uwsgi_pass unix:/opt/project/run/brmed_web.sock;
include uwsgi_params;
}
}If you need to also serve up other subdomains (www.mywebsite.com.br, etc.) you can set the server_name to ".mywebsite.com.br". | I'm using Django 1.5.1 in a production website but I'm having a huge number of 500's reports because of not allowed hosts requests. My website's Nginx vhost is configured as follows:server {
listen 80;
server_name mywebsite.com.br;
location / {
uwsgi_pass unix:/opt/project/run/brmed_web.sock;
include uwsgi_params;
}
}And I've set my allowed host settings onsettings.pyas:ALLOWED_HOSTS = ['mywebsite.com.br']Even though it works perfectly using my allowed host, I keep receiving erros as the following for stranges hosts:Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 92, in get_response
response = middleware_method(request)
File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py", line 57, in process_request
host = request.get_host()
File "/usr/local/lib/python2.7/dist-packages/django/http/request.py", line 72, in get_host
"Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): %s" % host)
SuspiciousOperation: Invalid HTTP_HOST header (you may need to set ALLOWED_HOSTS): 108.166.113.25Some of the hosts, if not all ot them, are clearly malicious since their requests are trying to trick with some PHP stuff. More detail about one of the hosts can be found inthis link.My question is, what am I missing on Nginx configuration that is allowing these requests with these strange hosts to pass? FYI my Nginx just has this config file and its default config file. | Avoiding Django's 500 error for not allowed host with Nginx |
The whole problem stems from trying to run nginx as my ordinary user self despite the fact that nginx was installed by my user self with administrative privileges. I was able to resolve both the errors shown here with the following commands executed as a user with administrative privileges:sudo chmod a+w /usr/local/var/log/nginx/*.log
sudo chmod a+w /usr/local/var
sudo chmod a+w /usr/local/var/runNote that the/usr/local/vardirectory appears to have been created by homebrew upon installing nginx and this machine is my laptop so I can’t see any reason not to open it up. You might have greater security concerns in other scenarios.I admit that when I wrote this question I thought it was about moving theerror.logfile to another directory. Now I see that that is not a full solution, so instead the solution I present here is about giving ordinary users write privileges in the necessary directories.The reason I changed my mind is that nginx can (and in this case does) generate errorsbefore(orwhile) reading thenginx.conffiles and needs to be able to report those errors to a log file. Modifying thenginx.conffile was never going to solve my problem. What woke me up to this issue was reading this post:How to turn off or specify the nginx error log location? | I assume I simply have to insert an entry into annginx.conffile to resolve the error that is plaguing me (see below), but so far I haven’t had any luck figuring out the syntax. Any help would be appreciated.I want to run nginx as a regular user while having installed it using homebrew as a user with administrative privileges. nginx is trying to write to theerror.logfile at/usr/local/var/log/nginx/error.log, which it cannot because my regular user lacks write privilege there.Another wrinkle is coming from the fact that there are twonginx.conffiles, a global and a local, and as far as I can tell they are both being read. They are in the default homebrew location/usr/local/etc/nginx/nginx.confand my local project directory$BASE_DIR/nginx.conf.Here is the error that is generated as nginx attempts to start up:[WARN] No ENV file found
10:08:18 PM web.1 | DOCUMENT_ROOT changed to 'public/'
10:08:18 PM web.1 | Using Nginx server-level configuration include 'nginx.conf'
10:08:18 PM web.1 | 4 processes at 128MB memory limit.
10:08:18 PM web.1 | Starting php-fpm...
10:08:20 PM web.1 | Starting nginx...
10:08:20 PM web.1 | Application ready for connections on port 5000.
10:08:20 PM web.1 | nginx: [alert] could not open error log file: open() "/usr/local/var/log/nginx/error.log" failed (13: Permission denied)
10:08:20 PM web.1 | 2017/03/04 22:08:20 [emerg] 19557#0: "http" directive is duplicate in /usr/local/etc/nginx/nginx.conf:17
10:08:20 PM web.1 | Process exited unexpectedly: nginx
10:08:20 PM web.1 | Going down, terminating child processes...
[DONE] Killing all processes with signal null
10:08:20 PM web.1 Exited with exit code 1Any help figuring out how to get nginx up and running so I can back to the development side of this project will be much appreciated. | How do I configure nginx to put its error.log file somewhere I have write privileges? |
It's now possible with Play2.0.2+:RequestHeader.remoteAddress()Java :String ip = request().remoteAddress();Scala :Action { request =>
val ip = request.remoteAddress()
} | For security reasons, sometimes it is needed to block users by IP. In my case, I would like to manage the IP blacklist in a (SQL) database. I guess I can handle the filter part based on Action Composition but for that I need the user's IP.So, how can I get the user's IP?PS : The application is running behind a nginx proxy. | How can you get a user's IP in PlayFramework2 ? |
Here's how I did it eventually - proxy_pass instead of curl - based on this:https://github.com/vorodevops/nginx-analytics-measurement-protocol/tree/master/lua. The code assumes openresty or just lua installed. Not sure if the comments format is compatible (didn't test) so it may be best to delete them before using it.# pick your location
location /example {
# invite lua to the party
access_by_lua_block {
# set request parameters
local request = {
v = 1,
t = "pageview",
# don' forget to put your own property here
tid = "UA-XXXXXXX-Y",
# this is a "unique" user id based on a hash of ip and user agent, not too reliable but possibly best that one can reasonably do without cookies
cid = ngx.md5(ngx.var.remote_addr .. ngx.var.http_user_agent),
uip = ngx.var.remote_addr,
dp = ngx.var.request_uri,
dr = ngx.var.http_referer,
ua = ngx.var.http_user_agent,
# here you truncate the language string to make it compatible with the javascript format - you'll want either the first two characters like here (e.g. en) or the first five (e.g en_US) with ...1, 5
ul = string.sub(ngx.var.http_accept_language, 1, 2)
}
# use the location.capture thingy to send everything to a proxy
local res = ngx.location.capture( "/gamp", {
method = ngx.HTTP_POST,
body = ngx.encode_args(request)
})
}
}
# make a separate location block to proxy the request away
location = /gamp {
internal;
expires epoch;
access_log off;
proxy_pass_request_headers off;
proxy_pass_request_body on;
proxy_pass https://google-analytics.com/collect;
} | Maybe this is trivial, but I haven't found anything meaningful or I didn't know where to look...(How) is it possible to to send a curl / whatever command as soon as a certain path is requested?Something along these lines, but that would actually work:location / {
curl --data 'v=1&t=pageview&tid=UA-XXXXXXXX-X&cid=123&dp=hit' https://google-analytics.com/collect
} | Can a http request be sent with the nginx location directive? |
I'm guessing you need a simple reverse proxy config.Lets say your go http server is listening onhttp://example.com:8080:server {
listen 80;
server_name example.com;
location / {
proxy_pass http://example.com:8080;
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 $scheme;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
} | I have a simple HTTP server written in Go.In development It works fine but for production, where this server has to handle 100 requests at a time I need a proper web server like nginx.How can I put it behind nginx? | How to run a Go http server with nginx |
if you're asking how to get the Amazon Linux-based Dockerfile to install curl without prompting you, you can add -y to yum update://Dockerfile for Amazon linux
FROM nginx
RUN yum -y update && yum install -y curl | The following Dockerfile few lines suppose to install curl inside the nginx custom image to run under ubuntu.The second group of code is an attempt to convert the task to do the same but to run on Amazon Linux.Any suggestion as to what would be the yum equivalent to the rest of the apt-get command?-no-install-recommends curl && rm -rf /var/lib/apt/lists/*//Dockerfile for ubuntu
FROM nginx
RUN apt-get update && apt-get install -y -no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*//Dockerfile for Amazon linux
FROM nginx
RUN yum update && yum install -y curl | Installing curl inside nginx docker image |
Sir, please try below code. :)server {
...
root /web/app/src;
...
location / {
try_files $uri $uri/ /index.html;
}
} | My root directory/web/app/srcIn this directory I have 2 directories /js/ and /assets/
and one file index.htmlThis is what I need to achieve:Any request to /js/ or /assets/ or /index.html just serve files from root directory
For example myapp.com/js/app.js servers app.js from /web/app/src/js/ directory
Same with requests to /assets/But all other requests, any other uri should result in serving index.htmlFor examplemyapp.com/bla/bla/q?param=x
Should serve index.html from web root directoryAll rewrites should be internal, no http 301 redirects. | How to redirect all request to same file in nginx? |
The following code worked for me (added before the "location ~ \.php$ {"-part:location /phpmyadmin {
root /usr/share/nginx/html;
location ~ ^/phpmyadmin/(.+\.php)$ {
try_files $uri =404;
root /usr/share/nginx/html;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include /etc/nginx/fastcgi_params;
}
location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ {
root /usr/share/nginx/html;
}
}Just make sure to adjust the three "root" locations to the folder where your "phpmyadmin" folder is in (the location of my phpmyadmin folder is here: "/usr/share/nginx/html/phpmyadmin" | I have the following nginx config on my LEMP droplet:server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /var/www/html/public;
index index.php index.html index.htm;
server_name server_domain_or_IP;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}I would like to run PHPMyAdmin together with Laravel on/phpmyadmin but only the Laravel routes get served to the browser. So any /phpmyadmin would be parsed as a route where it isn't one.I have tried multiple thingsAdding my own location/phpmyadminabove thelocation ~ \.phpeven trying^~ /phpmyadminto force precedence.I've set my root to /usr/share/phpmyadmin, without any results.I have tried copying the fastcgi options and basically copying the complete logic but using /phpmyadmin without any result eitherI am pretty sure it's probably a small thing that I am missing. | Laravel routes overwriting phpmyadmin path with nginx |
Finaly resolved. After logfile plugin turned on:LoadPlugin logfile
LogLevel info
File "/var/log/collectd.log"
Timestamp true
I found that nginx plugin is not installed:[2014-10-14 06:30:59] plugin_load: Could not find plugin "nginx" in /usr/lib64/collectd
[2014-10-14 06:30:59] Found a configuration for the `nginx' plugin, but the plugin isn't loaded or didn't register a configuration callback.Simply execute (AMI):$ sudo yum install collectd-nginxAnd all works perfectly | My collectd config looks like:LoadPlugin nginx
...
URL "http://localhost:8080/nginx_status?auto"
Nginx conf looks like:server {
listen 8080;
index index.html index.htm;
server_name localhost;
root /var/www/default/;
location / {
try_files $uri $uri/ /index.html;
}
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}When i execute$ curl http://localhost:8080/nginx_status?autoit outputs:Active connections: 1
server accepts handled requests
56 56 322
Reading: 0 Writing: 1 Waiting: 0But when open graphite there is no nginx graph avaliable.
Collectd and Nginx was restarted many times. Any suggestions? | Collectd and Nginx plugin not working |
Ok, found itcontent_by_lua '
local file = "/path..."
local f = io.open(file, "rb")
local content = f:read("*all")
f:close()
ngx.print(content)
'; | Having trouble with file output in Nginx + Lua. I chosen LUA, because nginx logic is pretty complicated, based on referrer or subdomains, etc.Having request like /img/am1/s/1.jpg I need to check if file exists in /somepath/am1/1.jpg. If it exists, then output it, otherwise proxy request to backend. | Nginx + LUA, how to output file? |
Okay, here's something. I don't know if it's the right way or not but I was able to fix the issue by manually sending theContent-LengthHeader from my RailsController. Here's what I'm doing:def download
@file = Attachment.find(params[:id])
response.headers['Content-Length'] = @file.size.to_s
send_file(@file.path, x_sendfile: true)
endnginxshould be automatically able to set the header. There must be something that I'm missing; but until I find a 'proper' solution, I guess this will have to do.P.S: The Header needs to be a string to work properly with some webservers, hence the.to_s | I've a rails app that serves large static files to registered users. I was able to implement it by following the excellent guide here:Protected downloads with nginx, Rails 3.0, and #send_file. The downloads and everything else is working great, but there is just this problem - TheContent-Lengthheader isn't being sent.It's okay for small files, but it gets really frustrating when large files are downloaded, since download managers and browsers don't show any progress. How can I fix this? Do I have to add something to mynginxconfiguration or do I have to pass along some other option to thesend_filemethod in my rails controller? I have been searching online for quite some time but have been unsuccessful. Please Help! Thanks!Here's mynginx.conf:upstream unicorn {
server unix:/tmp/unicorn.awesomeapp.sock fail_timeout=0;
}
server {
listen 80 default_server deferred;
# server_name example.com;
root /home/deploy/apps/awesomeapp/current/public;
location ~ /downloads/(.*) {
internal;
alias /home/deploy/uploads/$1;
}
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
try_files $uri/index.html $uri @unicorn;
location @unicorn {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Sendfile-Type X-Accel-Redirect;
proxy_set_header X-Accel-Mapping /downloads/=/home/deploy/uploads/;
proxy_pass http://unicorn;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 20M;
keepalive_timeout 10;
} | Content-Length Header missing from Nginx-backed Rails app |
Consider next setup:nginx -> ring server (jetty)You need to startlein ring server(usinglein-ringplugin) on some port (say 8080). Nginx will listen at 80 port and forward requests to 8080.
Here is a sample nginx config:upstream ring {
server 127.0.0.1:8080 fail_timeout=0;
}
server {
root ;
# Make site accessible from http://localhost/
server_name localhost;
location / {
# First attempt to serve request as file
try_files $uri $uri/ @ring;
}
location @ring {
proxy_redirect off;
proxy_buffering off;
proxy_set_header Host $http_host;
proxy_pass http://ring;
}
location ~ ^/(assets|images|javascripts|stylesheets|swfs|system)/ {
expires max;
add_header Cache-Control public;
}
}Changepath-to-public-dirto directory where your static files reside (resources/public).
Nginx will server static files (if file found) and forward other requests to ring server. | I set up a home server with ubuntu and ngingx and I can serve static files. Now I want to test some clojure files but I am not clear about how to do this. For php this seems very easy, for instancein this tutorialhe adds a location for php files. Is that all I need to do, just indicate where Clojure files are in the config file?I have theWeb Development with Clojureby Dmitry Sotnikov and he talks about deployment but not specifically about nginx.Can you point me in the right direction where I can find documentation about this? | How to serve Clojure pages with nginx |
As soon as I posted this it occurred to me that maybe apt wasn't updating first. Sure enough, I needed to have the apt cookbook installed and in the run list ahead of nginx. This solves the problem. | I am trying to get an nginx/unicorn ruby app server configured with chef. The problem I am running into is a dependency on the build-essential cookbook which when run, results in the output:================================================================================
Error executing action `install` on resource 'package[build-essential]'
================================================================================
Chef::Exceptions::Exec
----------------------
apt-get -q -y install build-essential=11.5ubuntu2 returned 100, expected 0I am still pretty new to chef and am not sure why this is happening. Any ideas? | Error with Chef build-essential cookbook on ubuntu 12.04 |
Nginx defaults to considering underscores in request headers invalid and subsequently removes them, seehttp://wiki.nginx.org/HttpCoreModule#underscores_in_headersfor how to fix this. | I'm running Rails 3.1 with PhusionPassenger and NGINX in the back. I'm sending requests via a simple HttpClient (GrahpicalHttpClient for OS X). My code expects a token and an ID in the header to verify the authenticity of the caller. In developement mode this is no problem, but once I move it into production the header variables go missing. Nothing is displayed.Here is the code:@caller = Person.check_authentication_token(request.headers['person_id'], request.headers['authentication_token'])The method check_authentication_token returns nil if either variable is nil. As I said, this works fine in development but the request.headers['person_id'] and request.headers['authentication_token'] are both nil in production. Has anyone else seen this issue before? | header variables go missing in production |
The default capacity is 100 messages and the default message expiration time is
60 seconds. So if the the channel is never read within these capacity / time
constraints, it will fill up.One reason why a channel might fill up is when the connection is never properly
closed. In this case the channel will remain in the group and eventually fill up.One way to mitigate this is to have enough capacity and a short timeout. You
can alter the configuration in the Django settings in the following way:CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": REDIS_URL, # or where your redis server lives
"capacity": 1500, # default 100
"expiry": 10, # default 60
}
}
} | I'm doing load testing with my Django app providing GraphQL Subscriptions using Django channels and a redis Channels layer (django,graphene-django,channels,graphene-subscriptions,channels-redis). As ASGI server I'm usingdaphneright now. I usenginxas proxy. The periodicity with which the backend publishes messages via GraphQL Subscriptions depends on the periodicity of messages the backend receives via MQTT. I'm increasing the periodicity with which an external data provider publishes messages to the MQTT broker, means the periodicity with which the backend has to process these messages and publish messages via GraphQL Subscriptions. I'm facing the following error:2020-03-11 08:33:58,464 ERROR 2 of 12 channels over capacity in group subscriptionsIt seems like this issue is caused bychannels_redis. Can I scale the infrastructure to workaround this issue? | Django channels "ERROR Y of N channels over capacity in group subscriptions" |
Hope this helps,In the http context of your NGINX configuration, add these lines:http {
... # your nginx.conf here
# Maps ip address to $limit variable if request is of type POST
map $request_method $limit {
default "";
POST $binary_remote_addr;
}
# Creates 10mb zone in memory for storing binary ips
limit_req_zone $limit zone=my_zone:10m rate=1r/s;
}
**Rate limiting for the entire NGINX process:**
http {
... # your nginx.conf here
limit_req zone=global_zone;
}REF:https://product.reverb.com/first-line-of-defense-blocking-bad-post-requests-using-nginx-rate-limiting-507f4c6eed7b | I have a server in nginx configured and have the following code to create my rate limit zone:limit_req_zone $key zone=six_zone:10m rate=60r/m;In my location, I use a module to serve the requests. This location supports GET, POST and DELETE methods. I am trying to rate limit only GET requests to that location. This is what I thought might work but it does not.location /api/ {
if ($request_method = GET) {
limit_req zone=six_zone;
}
reqfwder;
}Any help or pointers towards how I can approach this? Thanks. | Nginx Rate limit GET or POST requests only at a location |
you can add a script and use it in yourCMD:script :#!/bin/bash
service nginx start
php-fpm7add the script to yourDockerfile:COPY /PATH/TO/script.sh /path/in/container/script.sh
RUN chmod +x /path/in/container/script.sh
CMD ["/path/in/container/script.sh"] | I would like to run nginx and php-fpm on container start, however I can't seem to do that. Here is myDockerfile:FROM php:7-fpm-alpine
EXPOSE 9080 8000
EXPOSE 9088 80
WORKDIR /var/www
COPY . .
RUN apk add nginx composer php7-fpm && \
composer install --no-progress && \
mkdir -p /etc/nginx /etc/nginx/sites-available /etc/nginx/sites-enabled /run/nginx && \
ln -s /etc/nginx/sites-available/default.conf /etc/nginx/sites-enabled/default.conf && \
cp nginx.conf /etc/nginx/conf.d/default.conf
CMD ["nginx", "-g", "daemon off;"]Container comes up and running, however when I runps auxnginx is nowhere to be seen until I runnginxcommand (configuration is okay,nginx -treturns okay, and running it through open container does start the service).I've tried to chainRUN php-fpm7 && nginxbut that does nothing.Also using entrypoint likeENTRYPOINT ["nginx"]did nothing for me.How can I make sure those processes are running upon creating the container? | Running nginx on Alpine |
So I found the answer to this. It seems that as of Nginx v0.22.0 you are required to use capture groups to capture any substrings in the request URI. Prior to 0.22.0 using justnginx.ingress.kubernetes.io/rewrite-target: /worked for any substring. Now it does not. I needed to ammend my ingress to use this:apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/rewrite-target: /$1
creationTimestamp: "2019-04-03T12:44:22Z"
generation: 1
labels:
chart: app-1.1
component: app
hostName: app.client.com
release: app
name: app-ingress
namespace: default
resourceVersion: "1789269"
selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/app-ingress
uid: 34bb1a1d-560e-11e9-bd46-9a03420914b9
spec:
rules:
- host: app.client.com
http:
paths:
- backend:
serviceName: app-service
servicePort: 8080
path: /app1/?(.*)
tls:
- hosts:
- app.client.com
secretName: app-prod
status:
loadBalancer:
ingress:
- {} | I'm deploying a simple app in Kubernetes (on AKS) which is sat behind an Ingress using Nginx, deployed using the Nginx helm chart. I have a problem that for some reason Nginx doesn't seem to be passing on the full URL to the backend service.For example, my Ingress is setup with the URL ofhttp://app.client.comand a path of /app1g goinghttp://app.client.com/app1works fine. However if I try to go tohttp://app.client.com/app1/service1I just end up athttp://app.client.com/app1, it seems to be stripping everything after the path.My Ingress looks like this:apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/rewrite-target: /
creationTimestamp: "2019-04-03T12:44:22Z"
generation: 1
labels:
chart: app-1.1
component: app
hostName: app.client.com
release: app
name: app-ingress
namespace: default
resourceVersion: "1789269"
selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/app-ingress
uid: 34bb1a1d-560e-11e9-bd46-9a03420914b9
spec:
rules:
- host: app.client.com
http:
paths:
- backend:
serviceName: app-service
servicePort: 8080
path: /app1
tls:
- hosts:
- app.client.com
secretName: app-prod
status:
loadBalancer:
ingress:
- {}If I port forward to the service and hit that directly it works. | Kubernetes Nginx Ingress removing part of URL |
try:try_files $uri $uri/ /index.php?q=$uri&$args;AND:fastcgi_index /index.php;(note the / ) | Ran into a 500 issue when running Nginx and WP together and setting pretty permalinks. I've been trying a bunch of different methods from Google but none seems to help.Config -server {
listen 80;
root /var/www/mydomain.com/public_html;
index index.php index.html index.htm;
server_name .mydomain.com;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}All files load perfectly well, and the pages work if using the default permalinks setting. Strange thing is, if I check the network log I first see a 200 OK being received, then immediately followed by a 500. Any ideas?Edit: Setting to close as I'm switching to Apache instead. Will mark correct answer as it seems to have helped others. | 500 error with Nginx and WordPress pretty permalinks |
As root:lsof -i :443...should reveal the offending process ID, assuming you have lsof on your operating system. | I get this when I try to start nginx on ubuntu.[emerg]: bind() to 0.0.0.0:443 failed (98: Address already in use)How do I find and destroy process responsible? | How do I find and stop the process that is running a server on port 443 |
You need to make sure the server directive is inside of the http directive if I recall.eg:http {
//various nginx settings here
server {
//server stuff here
}
} | This is my first time using nginx and I'm having some problems configuring an nginx.conf file. What I have isserver {
location ~ /(application|system) {
deny all;
return 404;
}
rewrite ^(.*)$ /index.php/$1 break;
}In case it's not clear; I'm trying to block access to the directories application and system and rewrite all other requests to the index.php. I've tried validating the nginx.conf file using:ian@ubuntu:~$ sudo nginx -t -c path_to_conf_filebut get[emerg]: unknown directive "server".... Any ideas what I might be doing wrong? | Problems with nginx.conf |
more_set_headersis a part of theheaders_moremodule, so it needs an additional nginx package to work properly.nginx-extrascould be installed while building docker image for nginx container:FROM nginx:1.15.6
RUN apt-get update && apt-get install -y nginx-extrasHope this helps. | I install nginx:1.15.6 container by docker-compose file and I want to remove Server header from all nginx responses, by the search I found bellow way
set "more_set_headers 'Server: custom';" in nginx configuration but there is an error to respond . How can I remove server header in nginx docker? I think I should install "headers-more-nginx-module-0.33" module but I dont know how can i install it :(error :[emerg] 1#1: unknown directive "more_set_headers" in /etc/nginx/conf.d/default.conf:22docker-compose file:version: '3'
services:
web:
build:
context: nginx
container_name: r_nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./code:/code
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf
- ./nginx/ssl:/etc/ssl
- ./nginx/logs:/var/log/nginx
restart: always
depends_on:
- php
php:
build: phpfpm
container_name: r_php
restart: always
volumes:
- ./phpfpm/raya.ini:/opt/bitnami/php/etc/conf.d/custom.ini
- ./code:/codedefault.conf :server_tokens off;
server {
listen 80;
listen 443 ssl;
ssl on;
ssl_protocols TLSv1.1 TLSv1.2;
ssl_certificate /etc/ssl/cert_chain.crt;
ssl_certificate_key /etc/ssl/private.key;
index index.php index.html;
#server_name php-docker.local;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
root /code;
error_page 404 403 402 401 422 = /errors/error.php;
error_page 500 501 502 503 504 = /errors/error.php;
# bellow line get error :
# more_set_headers "Server: custom";
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
location ~ /assets/ {
}
location / {
rewrite ^(.*)$ /index.php;
}
} | How can I remove server header in nginx docker container? |
You need to enable WebSocket proxying to allow the editor to connect back to the runtime.To do that you need to add some additional options to yourlocationconfigs:location / {
proxy_pass "https://127.0.0.1:8080";
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}For more information about NGINX and WebSockets, refer to the documentationhere. | Greetings I am configuring a node-red server and after apply Nginx redirect I got the following issue.After Using Nginx to redrect subdomain node-red.domain.com to localhost:1880Nginx redirect config:server {
listen 80;
server_name sub1.domain.com;
location / {
proxy_pass "https://127.0.0.1:8080";
}
}
server {
listen 80;
server_name sub2.domain.com;
location / {
proxy_pass "https://127.0.0.1:8080";
}
}Please anyone can help me on that? | nginx make node-red Lost connection to server but deploy works |
Use curl localhost:5601 to test if kibana is really working.
If not working , go to etc/kibana/ to modify the config to check if host is 0.0.0.0 and port is 5601
And the other problem is that your server'memories are not enough for kibana starting.
Hope you can provider the kibana log.try use:journalctl -u kibana.serviceto show the log. | I am trying to install Elastic search, Nginx, Kibana and Sense.I am following this guide:https://www.digitalocean.com/community/tutorials/how-to-install-elasticsearch-logstash-and-kibana-elk-stack-on-ubuntu-14-04I successfully installed Elastic search.However I am stuck at Kibana.I successfully followed all steps however:root@dev:~# service kibana start
kibana started
root@dev:~# service kibana status
kibana is not runningWhen I run kibana service it says it started, and after that when I want to check if kibana is running, it says it is not running.If more details are needed for this question to be answered, comment and I will provide it. | kibana service not running |
Indeed, when you are enabling Jelastic SSL (means you can't use public IP) shared resolvers processing all requests to your server but between resolver and your server requests are not https. So with redirect, you tried to set up, your server redirected incoming http requests to https and sent it back to resolver, as result you've got a loop redirect.You need to perform a few simple steps to resolve this issue.
Login to dashboard, open settings for nginx balancerNavigate to nginx-jelastic.conf under /confand add the code to the configuration file:# force https-redirects
if ($http_X_Forwarded_Proto = http) {
return 302 https://$host$request_uri;
}Do not forget to press the "Save" button and restart the nginx after the configuration was made. | I have an account in Jelastic and I want to force my site to work only over https. I've created environment nginx + php with nginx balancer and enabled Jelastic SSL (as it describedhere).Whenever I tried to setup 301 redirect from http to https with no luck. Using mod_rewrite didn't work for me, the only thing I've got is a loop redirect. Google didn't help.I really need advise. Any additional info will be provided.Thanks in advance. | Jelastic Nginx http to https redirect |
Typically, you dedicate a container for authentication, with for instance NGiNX.This is described in "Authenticating proxy with nginx", which not only adds the basic authentication, but also ssl (https)That web server will then reverse proxy to your container.You have a more generic solution (based on a reverse-proxy NGiNX) withjwilder/nginx-proxynginx-proxy sets up a container running nginx anddocker-gen.docker-gengenerates reverse proxy configs for nginx and reloads nginx when containers are started and stopped.See the use case with "Automated Nginx Reverse Proxy for Docker". | Consider running a Docker container with a web application exposing a certain port. How to apply the additional security layer before accessing the URL (HTTP BASIC AUTH)?Docker Engine version >= 1.9.1 | Securing a Docker container with HTTP BASIC AUTH |
Turns out that thumbnail requests returned from Dropbox include the headerCache-Control: no-cacheand Nginx will adhere to these headersunless they are explicitly ignoredwhich can be done by simply using the following config line that will ignore any caching control.proxy_ignore_headers X-Accel-Expires Expires Cache-Control;We also had issues placing the "proxy_ignore_headers" option in different areas within the nginx.conf file. Finally after much playing around we got it to work by explicitly setting it in the "location" block. The full snippet of the config file can be found below## Proxy Server Caching
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=STATIC:50m inactive=2h max_size=2g;
## Proxy Server Setting
server {
listen *:8181;
location ~ ^/(.*) {
set $dropbox_api 'api-content.dropbox.com';
set $url '$1';
resolver 8.8.8.8;
proxy_set_header Host $dropbox_api;
proxy_hide_header x-dropbox-thumbcachehit;
proxy_hide_header x-dropbox-metadata;
proxy_hide_header x-server-response-time;
proxy_hide_header x-dropbox-request-id;
proxy_hide_header cache-control;
proxy_hide_header expires;
add_header cache-control "private";
add_header x-cache $upstream_cache_status; # HIT / MISS / BYPASS / EXPIRED
proxy_cache STATIC;
proxy_cache_valid 200 1d;
proxy_cache_use_stale error timeout invalid_header updating
http_500 http_502 http_503 http_504;
proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
proxy_pass https://$dropbox_api/$url$is_args$args;
}
} | I'm having issues getting NGINX to cache thumbnails that I'm pulling from Dropbox using the proxy_pass command. On the same server that NGINX is running I run the following command multiple timeswget --server-response --spider http://localhost:8181/1/thumbnails/auto/test.jpg?access_token=123and get the exact same response with X-Cache: MISS every timeHTTP/1.1 200 OK
Server: nginx/1.1.19
Date: Wed, 25 Mar 2015 20:05:36 GMT
Content-Type: image/jpeg
Content-Length: 1691
Connection: keep-alive
pragma: no-cache
cache-control: no-cache
X-Robots-Tag: noindex, nofollow, noimageindex
X-Cache: MISSHere's my meat of my nginx.conf file .. any ideas on what I'm doing wrong here?## Proxy Server Caching
proxy_cache_path /data/nginx/cache keys_zone=STATIC:10m max_size=1g;
## Proxy Server Setting
server {
listen *:8181;
proxy_cache STATIC;
proxy_cache_key "$request_uri";
proxy_cache_use_stale error timeout invalid_header updating
http_500 http_502 http_503 http_504;
location ~ ^/(.*) {
set $dropbox_api 'api-content.dropbox.com';
set $url '$1';
resolver 8.8.8.8;
proxy_set_header Host $dropbox_api;
proxy_cache STATIC;
proxy_cache_key "$request_uri";
proxy_cache_use_stale error timeout invalid_header updating
http_500 http_502 http_503 http_504;
add_header X-Cache $upstream_cache_status;
proxy_pass https://$dropbox_api/$url$is_args$args;
}
##Error Handling
error_page 500 502 503 504 404 /error/;
location = /error/ {
default_type text/html;
}
} | NGINX proxy_pass not caching content |
This is the sites-enabled NGINX server configuration that ended up working for me...server {
listen 80;
server_name registration.app;
root /home/vagrant/Code/registration/public;
charset utf-8;
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/registration.app-error.log error;
error_page 404 /index.php;
sendfile off;
# Point index to the Laravel front controller.
index index.php;
location / {
try_files $uri $uri/ index.php?$query_string;
}
location ~ \.php$ {
try_files $uri /index.php =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
#deny all;
}
} | Laravel is not receiving any $_GET variables from the URL query string. The $_GET and Input::all() are empty.Example:example.app/ex/login.php?country=USThe "country=US" never shows up in my $_GET variableAfter much research and trying many different NGINX configurations, I can now only produce results when this example is used.Example:example.app/index.php/ex/login.php?country=USThe $_GET variable now shows the country name value pair.What is the proper configuration to allow query strings within the URL?My current sites-enabled configuration for my "example.app" is...server {
listen 80;
server_name example.app;
root /home/vagrant/Code/public;
index index.html index.htm index.php;
charset utf-8;
location / {
#try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/registration.app-error.log error;
error_page 404 /index.php;
sendfile off;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors on;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
}
location ~ /\.ht {
deny all;
}} | Laravel 5 - NGINX Server Config Issue with URL Query Strings |
Everything looks right. Can you try usingphp-fpmwith the exact same ngingx config and see if it works? Maybe you have a directory permission issue or something. Also make sure you are actually starting thehhvm-fastcgiprocess using/etc/init.d/hhvm-fastcgi startand that nothing was listening on port 9000 before you ran that. You can runps auxf | grep hhvmto make sure it is running and listening. | I would like to use HHVM via Nginx. (Ubuntu 12.04.2 LTS, PHP 5.3.10)I've followed the steps mentioned here:http://www.hhvm.com/blog/1817/fastercgi-with-hhvmThis is how my Nginx setup looks:server {
listen 80;
server_name demo1.dev
server_name_in_redirect off;
root /var/www/demo1;
location / {
index index.php;
try_files $uri $uri/ @handler;
expires 30d;
}
location @handler {
rewrite / /index.php;
}
location ~ .php$ {
fastcgi_keep_conn on;
if (!-e $request_filename) { rewrite / /index.php last; }
expires off;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param PHP_VALUE "error_log=/var/report/PHP.error.log";
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 1y;
log_not_found off;
}
}I have a file called hhvm.php that contains this:function is_hhvm() {
return defined('HHVM_VERSION');
}
if (is_hhvm()) {
echo "HHVM is working\n";
} else {
echo "HHVM is not working\n";
}What am I doing wrong and how can I see if HHVM is working properly?UPDATE:
Output of:ps auxf | grep hhvmroot 15164 0.0 0.0 9360 660 pts/0 S+ 13:55 0:00 \_ grep --color=auto hhvm
www-data 15142 4.2 6.3 576564 122484 ? Ss 13:54 0:01 /usr/bin/hhvm --config /etc/hhvm/server.hdf --user www-data --mode daemon
www-data 15154 7.0 6.3 580668 122636 ? Ss 13:54 0:01 /usr/bin/hhvm --config /etc/hhvm/server.hdf --user www-data --mode daemon -vServer.Type=fastcgi -vServer.Port=9000 -vPidFile=/var/run/hhvm/hhvm-fastcgi.pid | HHVM with Nginx fastcgi not working properly |
If you havefastcgi_cache_path /tmp/nginx keys_zone=myzone:8mjust callrm -Rf /tmp/nginx/*It's really as simple as this: When you want to clean the cache, clean the cache :) (That in this case is just a folder) | Is there a built-in way to clear the Nginx fastcgi_cache with PHP? I know I can write a PHP script that goes through and manually deletes all the cache files, but that seems too much like a hack. | How do I clear fastcgi_cache with PHP? |
Martin,In general, Nginx is better for high-traffic sites due to its event-driven architecture. Rather than handling each request in a distinct thread, it uses non-blocking I/O to service many requests in each thread.The important aspect of this architecture is the reduced use of processes or threads. A thread can consume anywhere from 2MB to over 64MB of RAM. So when Apache serves a 10KB JPEG, it may actually be using a significant amount of RAM. It becomes worse if you have slow clients (e.g. smartphones) where the request may keep a thread busy for several seconds.Many people find that running Nginx as a proxy in front of Apache to be an ideal middle ground. Nginx talks to the slow clients and can do so using a very small amount of RAM. When requests are forwarded to Apache, the request speed is limited by your local connectivity, not that of the remote user. This means that the network bottleneck will not keep the request (and it's memory-hogging thread) alive for any longer than necessary.In short you get the low-resource benefits of Nginx coupled with the wide feature-set of Apache. | Wouldnginxbe a more suitable choice as a web server for high traffic websites?The site we will be building is an e-commerce site, if that makes a difference.I am really interested in the actual 'why' from a technical point of view either way. i.e., why wouldnginxbe a better choice for this type of site from a technical standpoint, or the opposite, why it wouldn't? | Nginx v Apache for high traffic sites |
Fromthe Django docs:DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that's how it's gonna stay. We're in the business of making Web frameworks, not Web servers, so improving this server to be able to handle a production environment is outside the scope of Django.)So, that answers the latter two questions. As for the former, it depends on how your debug server is set up. If your server is exposed to the public Internet, doesn't have a firewall blocking port 8000, and you intend to userunserverwith something other than the default 127.0.0.1 address, set up a more 'proper' application stack.If you're going to use nginx, why not just use thesuggested FastCGI configurationso that your debug environment will be more similar to the future production environment? | Concerning the built in debugging server started with themanage.py runservercommand, the Django docs state, "DON’T use this server in anything resembling a production environment."If I wanted to develop a Django application over ssh on a remote machine, would using Nginx as a proxy to a running Django debug server be a reasonable thing to do? Is the Django debug server insecure, or just not built to handle large amounts of traffic? | How dangerous is Django's built in test server when run remotely? |
Solved it myself. If anyone is looking for the same solutionlocation ~* /amp/. {
deny all;
} | I want to block access to urls that have excess characters at its end.E.g. I want nginx to block requests tohttps://www.example.com/url-pattern/amp/extra-chars/more-extrabut want it to allowhttps://www.example.com/url-pattern/amporhttps://www.example.com/url-pattern/amp/Will this work?location .*\/amp\/. {
deny all
}Please guide. | Regex to block url in nginx |
Thenginxsetting you are trying to use (/etc/nginx/conf.d/proxy.conf) is forAmazon Linux 1.Since you are usingAmazon Linux 2you should be using different files for setting nginx. For AL2, the nginx settings should be in.platform/nginx/conf.d/, not in.ebextentionsas shown in thedocs.Therefore, you could have the following.platform/nginx/conf.d/myconfig.confwith content:client_max_body_size 20M;The above isan exampleonly of the config file. I can't verify if the setting will actually work, but you are definitely using wrong folders to set nginx options.My recommendation would be to try to make it work manually through ssh as you are attempting now. You may find that you need to overwrite entire nginx setting if nothing works by providing your own.platform/nginx/nginx.conffile. | I have a Node 10 app running on Elastic Beanstalk, and it throws 413 errors when the request payload is larger than ~1MB.
413 Request Entity Too Large
413 Request Entity Too Large
nginx/1.16.1
The request is not hitting my app at all; it's being rejected by nginx.I have tried configuring AWS to increase the size of the allowed request body based onthis answer, to no avail.I've tried adding a file at.ebextensions/01_files.configwith the contents:files:
"/etc/nginx/conf.d/proxy.conf" :
mode: "000755"
owner: root
group: root
content: |
client_max_body_size 20M;That didn't work, so I tried adding the file directly to.ebextensions/nginx/conf.d/proxy.confwith only:client_max_body_size 20M;And this also didn't work. Then I SSH'ed into the instance and added the file directly. Upon re-deploy, the entireconf.ddirectory was deleted and re-written, without this file.How can I get AWS Elastic Beanstalk with Node.js 10 running on 64bit Amazon Linux 2/5.1.0 to accept nginx configuration? | Configuring nginx client_max_body_size on Elastic Beanstalk Node |
The order of precedence oflocationis described herehttps://nginx.org/en/docs/http/ngx_http_core_module.html#locationWhen an exact match is found (using the=modifier) the search terminates and regular expressions will not be checked, so you can use that for yoursw.js:location = /sw.js {
add_header Cache-Control "public, max-age=0, must-revalidate";
} | I'm setting up a Nginx sever (version 1.17.1) for Gatsby following up the recommendation athttps://www.gatsbyjs.org/docs/caching/.The snippet below is the portion myserver {}block attempting implementing the recommended caching configuration;location ~* \.(?:html)$ {
add_header Cache-Control "public, max-age=0, must-revalidate";
}
location /static {
add_header Cache-Control "public, max-age=31536000, immutable";
}
location ~* \.(?:css|js)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
location /sw\.js {
add_header Cache-Control "public, max-age=0, must-revalidate";
}Equally tried anif statementin place of thelocation {}block for defining cache configuration for the service worker file,sw.js, as below;if ($request_uri ~ ^sw\.(?:js)$) {
set $no_cache 1;
}Unfortunately, all files get cached successfully as expected exceptsw.js.What am I doing wrong and how can I fix it so as to effectively set cache control header forsw.jstopublic, max-age=0, must-revalidate? | Define specific cache control header for selected file only |
As Terrence said: Nginx alias path Cannot be a temporary path. eg:/tmp/** | When I request a linkhttp://abc.example.com/images/default-thumbnail.jpga 404 error occurs while seeing the log file output[error] 1244#0: *1 open() "/tmp/upload-dir/images/default-thumbnail.jpg" failed (2: No such file or directory),But in fact this file is there,And the authority is 777[root@localhost nginx]# ll /tmp/upload-dir/images/default-thumbnail.jpg
-rwxrwxrwx 1 root root 7592 6月 21 2016 /tmp/upload-dir/images/default-thumbnail.jpgNginx configuration:server {
charset utf-8;
client_max_body_size 128M;
sendfile off;
listen 80;
server_name abc.example.com;
access_log /www/abc/logs/nginx-access.log;
error_log /www/abc/logs/nginx-error.log;
root /tmp/upload-dir;
location /images/ {
autoindex on;
expires 30d;
}
location / {
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
}
} | open() "" failed (2: No such file or directory) |
But right now if I go directly to the ports the apps are running on
(localhost:3000) I can access them that way too.Thats because you are using-paka--publishcommand in yourdocker runExplanation:If you want to expose ports between containers only, Do Not use-por--publishjust put them on the same docker network.Example:Lets create a new user-defined network:sudo docker network create appnetLets create nginx container for reverse proxy, It should be available to outside world so we use publish.sudo docker run --name nginx -d --network appnet nginxNow put your apps in the same network but do not expose ports.sudo docker run --name app1 -d --network appnet | I have a few apps running in a Docker network with their ports (3000,4200, etc) exposed. I also have an nginx container running within the same Docker network which hosts these apps on port80with different domain names (site1.com,site2.com).But right now if I go directly to the ports the apps are running on (localhost:3000) I can access them that way too.How do I expose those ports only to the nginx container and not the host system? | How to expose ports only within the docker network? |
/etc/nginx/nginx.confis not the place to store your server setups. This file should contain information on the user it will run under and other global settings. Typically it will contain stuff like this:user www-data;
worker_processes 4;
pid /run/nginx.pid;
events {
worker_connections 768;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off;
client_max_body_size 500M;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
gzip_disable "msie6";
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}Where you should put your individual server setups, is in/etc/nginx/sites-enabled/. As you can see, all files inside that folder are being included in thehttpblock of yournginx.conffile.So store the sample config you have posted inside/etc/nginx/sites-enabled/some-random-name.conf, and restore thenginx.conffile to the config I posted above, for instance, and you should be good to go. | Yet starting nginx fails and my log shows:[emerg] 55#55: "server" directive is not allowed here in /etc/nginx/nginx.conf:1What am I doing wrong? Not sure if it matters but this is inside a docker container. | why does nginx fail to start? |
I think the best option is to use a suite of Logstash (event collecting) + Elasticsearch (event storage) + Kibana (analytics). All three are really good opensource projects with a lot of documentation and very active communities.And if you need commercial support for any you can request help from:http://www.elasticsearch.org/Logstash its flexible enough to allow you parse many log file formats out of the box. Moreover, storing all your logs on elastic search will allow you to create custom queries, reports and stuff.You can check a kibana demo on:http://demo.kibana.org/Links:http://www.elasticsearch.org/overview/kibana/http://logstash.net/ | I develop and maintain a paywalled publication with 2000+ users. The most common support request relates to log in. Most times these can be solved with a couple of support emails. Every once in a while though, there's that odd user that just can't log in. As a last resort the support person resets the users password, verify that they can log in themselves and send the new credentials of to the user. Every now and then we get at user that still can not log in. At that point I'm out of troubleshooting tools.So I'd like to have a tool that:Logs all HTTP requests in full (except for users passwords).Let's me search the log for a POST request to my login page containing the users name.Let me look at all requests from the IP-address that I found in step 2 within a certain timeframe, and then analyse those requests very closely.And I need to be able to do smart log rotation, like: "Hang on to everything you can fit into 30 GB, then start throwing out the old stuff".Our publication happens to be built with Django and nginx, but I don't think that the tool I'm looking for will be specific to those tools. And I definitely don't want to throw all the request data in the same SQL database as my Django app.So far I've foundLogstash, but I haven't look at it closely enough to know if it's right for me. The important thing to me isn't to get nice graph of all usage, user trends, conversion funnels etc. What I need is better ways to troubleshoot a problem that's affecting a single user. | How to do HTTP request logging as a means of troubleshooting login errors |
location / {
rewrite ^(.*)$ /index.php?u=$1 last;
} | URL rewrite is not working in Nginx and operating system is Ubuntu 12.4 Ltswhen openhttp://mvc.locit is working
but when i try to openhttp://mvc.loc/loginNot working404 Not Foundnginx/1.1.19.htaccess
ErrorDocument 500 "mod_rewrite must be enabled"
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?u=$1virtual hosts for mvc.locserver {
listen 80;
server_name mvc.loc;
access_log /var/log/nginx/mvc.loc.access.log;
error_log /var/log/nginx/mvc.loc.error.log;
root /usr/share/nginx/www/mvc;
index index.php;
# use fastcgi for all php files
# Are you sure you have this set up?
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# deny access to apache .htaccess files
location ~ /\.ht {
deny all;
}
} | URL Rewrite is not working in Nginx |
NOTE: I assume that you meant anonymous read-only access; there is no way to distinguish between clone and fetch in git, I think.Do you want to set up "smart" HTTP (recommended), or "dumb" HTTP one?For "dumb" HTTP it is enough to forbid (or just do not set up) WebDAV - this is how pushes come with "dumb" HTTP (no git on server side).For "smart" HTTP follow directions foranonymous read access but authenticated write accessingit-http-backendmanpage, translating it from Apache to nginx, and modifying slightly. Note that documentation for anonymous read but authenticated write might be incomplete, but you do not worry about authenthicated write (push) access succeding anyway, isn't it? | how can I have a remote git repo which is accessible via httpbut only for cloning?
Maybe with the help of nginx (already running) andgit-http-backend(git-http-fetch?). | Setting up read-only http access to git repo |
edit2:http://wiki.nginx.org/HttpProxyModule#proxy_redirecthttp://wiki.nginx.org/HttpProxyModule#proxy_passWhat I think is happening is when you use yourhttpresponseredirect, theHTTP_HOSTheader is giving it the127.0.0.1:8080, because of yourproxy_passsetting.Django's HttpResponseRedirect seems to strip off my subdomain?Django has some methods it always
applies to a response. One of these is
django.utils.http.fix_location_header.
This ensures that a redirection
response always contains an absolute
URI (as required by HTTP spec). | As the title described, Django keeps changing my URL from/localhost/to/127.0.0.1:8080/which keeps messing up my serving static files by Nginx. Any ideas why its doing this? Thanks!/**EDIT**/
Here is the Nginx configuration:server {
listen 80; ## listen for ipv4
listen [::]:80 default ipv6only=on; ## listen for ipv6
server_name localhost;
access_log /var/log/nginx/localhost.access.log;
location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
{
root /srv/www/testing;
}
location / {
proxy_pass http://127.0.0.1:8080/;
proxy_redirect off;
}
location /doc {
root /usr/share;
autoindex on;
allow 127.0.0.1;
deny all;
}
location /images {
root /usr/share;
autoindex on;
}Here is Apache config file:
ServerName testing
DocumentRoot /srv/www/testing
Order allow,deny
Allow from all
WSGIScriptAlias / /srv/www/testing/apache/django.wsgi
| Django keeps changing URL from http://localhost/ to http://127.0.0.1:8080/ |
After way to long time spending debugging this issue, I finally got it working.
I found this project:https://github.com/waelkdouh/DockerizedClientSideBlazor/and started comparing. Only thing different I could see, what he had a .dockerignore
I made a copy of it and it all started working. Have no idea what was the issue. Can't see how any of the files listed could break the CSS..... | I have a strange issue, where my styling is broken when I try to host my blazor WASM project using Nginx. I tried to follow a couple of different guides and they were similar and had same issue for me.I have the code here:https://github.com/TopSwagCode/Dotnet.IdentityServer/tree/master/src/BlazorClientWhen I debug locally or publish locally and serve from dotnet serve I get the following:But when I publish and try to run it within docker using Nginx I get this:My buttons are still there, but I can't see them since they are white.My dockerfile is pretty simple:FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build-env
WORKDIR /app
COPY . ./
RUN dotnet publish -c Release -o output
FROM nginx:alpine
WORKDIR /var/www/web
COPY --from=build-env /app/output/wwwroot .
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80My nginx configevents { }
http {
include mime.types;
types {
application/wasm wasm;
}
server {
listen 80;
# Here, we set the location for Nginx to serve the files
# by looking for index.html
location / {
root /var/www/web;
try_files $uri $uri/ /index.html =404;
}
}
}I can't find any "not found" or similar in network tab.Edit:When comparing both running side by side, I was not able to find CSS for linear-gradient, which is the purple side of the menu. Digging a bit deeper, it seems all CSS in MainLayout.razor.css was not being found.https://github.com/TopSwagCode/Dotnet.IdentityServer/blob/master/src/BlazorClient/Shared/MainLayout.razor.cssWhen running locally:When running using Docker+NginxSo seems to me, the CSS is missing somehow???Edit 2:The build hash for CSS seems to not match after deploy.
So I found the CSS file linked on my Page to be like the following:But my HTML doesn't match that. It looks like this:Don't know how that can break during build and deploy for Docker+Nginx??? Is there something I am doing wrong in my dockerfile??? | Blazor WASM styling missing when hosted in docker using nginx |
Update:Beanstalk on Amazon Linux 2 AMI has a little different path for NGINX config extensions:.platform/nginx/conf.dThere you can place NGINX config extension files with*.confextension, for example:.platform/nginx/conf.d/upload_size.conf:client_max_body_size 20M;Documentation for this ishere.Original answer:Nginx normally does not read config from where is serves the content. By default all config nginx read is/etc/nginx/nginx.confand this file includes other files from/etc/nginx/conf.d/with*.confextension.You need to placeclient_max_body_size 40M;there. | I'm trying to increase the size of uploadable files to the server. However it seems there's a cap that prevents anything over 1MB of being uploaded.I've read a lot of answers and none have worked for me.I've done everything in this questionStackoverflow questionI did everything here as well.AWS resourceHere's what I have as the full error2021/01/15 05:08:35 [error] 24140#0: *150 client intended to send too large body: 2695262 bytes, client: [ip-address-removed], server: , request: "PATCH /user HTTP/1.1", host: "host.domain.com", referrer: "host.domain.com"I've made a file in this directory (which is at the root of my source code).ebextensions/nginx/conf.d/myconf.confIn it I haveclient_max_body_size 40M;I know that EB is acknowledging it because if there's an error it won't deploy it.
Other than that I have no idea what to doDoes anybody know what might be the issue here?Edit: backend is nodejs v12Edit: Also tried this inside of a .conf file in .ebextensionsfiles:
"/etc/nginx/conf.d/myconf.conf":
mode: "000755"
owner: root
group: root
content: |
client_max_body_size 20M; | client intended to send too large body EB Nginx |
The Docker way to do this would be to have two containers for the two services. Docker-compose is a tool that helps manage multi-container applications.The following docker-compose.yml should work for you:version: '3'
services:
app:
build:
context: ./dotnet
dockerfile: Dockerfile
expose:
- "80"
proxy:
build:
context: ./nginx
dockerfile: Dockerfile
ports:
- "80:80"
links:
- appBasically we expose the port for your app so the Nginx container can access it, and then we bind the port on the Nginx container to the one on your host machine.You put your Dockerfile and app in the "dotnet" folder, and your NginX logic in the /nginx/Dockerfile file.EDIT: If you would really like to have both services in a single container you can use the following:FROM microsoft/dotnet:2.1-aspnetcore-runtime
ENV ASPNETCORE_URLS https://*:8080
RUN apt update && \
apt install nginx
ADD nginx-website.conf /etc/nginx/sites-enabled
RUN service nginx restart
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "testapi.dll"]At this point you just need to create the Nginx config file "nginx-website.conf" and set up the reverse proxy for port 80 to 8080. | I'm currently running a docker container for an ASP.NET Core WebAPI project.
This web service is currently exposed on port 80.My dockerfile looks like this:FROM microsoft/dotnet:2.1-aspnetcore-runtime
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-obj/Docker/publish} .
ENTRYPOINT ["dotnet", "testapi.dll"]I'd like to install nginx as a layer between the service and the exposed public network.The final result should be ASP.NET running on port 90 which is internal only and an nginx webserver forwarding the local 90 to public 80 port.Is this possible? if so, how can I achieve such architecture? btw, I'm completely aware of the overhead caused by an extra layer.Thanks! | Install nginx on an existing asp.net core docker container |
I discovered that DOCUMENT_ROOT can not be reset.
I normally have scripts directories away from publicly accessible paths.
I knew that the scripts directory was the same level the web directory so I tried.location ~ (\.cgi|\.py|\.sh|\.pl|\.lua)$ {
gzip off;
autoindex on;
fastcgi_pass unix:/var/run/fcgiwrap.socket;
fastcgi_param SCRIPT_FILENAME $document_root/../scripts/$fastcgi_script_name;
include fastcgi_params ;
}which resolved the issue. | I've got a simple script cpuinfo.sh that works and is executable.I'm getting an error*224 FastCGI sent in stderr: "Cannot get script name, are DOCUMENT_ROOT and SCRIPT_NAME (or SCRIPT_FILENAME) set and is the script executable?" while reading response header from upstream, client: 86.44.146.39, server: staging.example.com, request: "GET /cpuinfo.sh HTTP/1.1", upstream: "fastcgi://unix:/var/run/fcgiwrap.socket:", host: "staging.example.com"the nginx settings arelocation ~ (\.cgi|\.py|\.sh|\.pl|\.lua)$ {
gzip off;
autoindex on;
fastcgi_pass unix:/var/run/fcgiwrap.socket;
include fastcgi_params;
fastcgi_param DOCUMENT_ROOT /home/balance/balance-infosystems-web/scripts/;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}I'm expecting fcgiwrap to execute/home/balance/balance-infosystems-web/scripts/cpuinfo.shI hard coded the script path to debug but I'm still getting the same error.location ~ (\.cgi|\.py|\.sh|\.pl|\.lua)$ {
gzip off;
autoindex on;
fastcgi_pass unix:/var/run/fcgiwrap.socket;
include fastcgi_params;
fastcgi_param DOCUMENT_ROOT /home/balance/balance-infosystems-web/scripts/;
# fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_FILENAME /home/balance/balance-infosystems-web/scripts/cpuinfo.sh;
}What needs to be changed in the nginx server config to execute the script correctly? | How to set DOCUMENT_ROOT and SCRIPT_NAME correctly for fcgiwrap |
Create the page with the specific slug in the Ghost backend.Create the.hbs-file named like this:page-about.hbs.FromGhost Documentation on custom pages:For example, if you have an 'About' page with the url/about/, adding a template calledpage-about.hbswill cause that template to be used for the about page, instead ofpage.hbs, orpost.hbs.These templates exist in a hierarchy. Ghost looks for a template which matches the slug (page-:slug.hbs) first, then looks forpage.hbsand finally uses post.hbs if neither is available. | I'm looking to add some more .hbs files to ghost/custom/themes/casper, such as an about page and landing page. This way, all files are using the same default layout and I have a /blog destination for my blog.However, when I create an .hbs file, such as about.hbs, and give it the same code as in page.hbs, and upload it to the theme folder, when I go to my-url.com/about, it gives a 404.So, how can I create custom .hbs pages? | Create custom pages on Ghost |
Finally solved thishere. I want to thank Miguel from laracast discussion.You need to change your configuration file under:/etc/nginx/sites-enabledchange linefastcgi_passforfastcgi_pass unix:/run/php/php7.0-fpm.sock;php7.0-fpm.sockis located under:/var/run/phpSince the new VM uses php 7.* and your configuration file might have the php location for 5.6 version.Then restart Nginx and PHPsudo service nginx restart
sudo service php7.*-fpm restart7.3 and the xdebug version in Homestead 8..* are incompatible. Further info foundhere* | Did google and various other search engines but still could not sort it out.
Here is my scenario:Larave 5 on homestead1)ps -eo pid,comm,euser,supgrp | grep nginx[following is the output ]2333 nginx root root
2335 nginx vagrant adm,cdrom,sudo,dip,www-data,plugdev,lpadmin,sambashare,vagrant2) Based on some search result, did make the following on :/etc/php/7.0/fpm/pool.dlisten.owner = www-datalisten.group = www-datalisten.mode = 06603) Output with sudo service php7.0-fpm restartRestarting PHP 7.0 FastCGI Process Manager php-fpm7.0 [ OK ]4) Output withsudo service nginx restartnginx stop/waitingnginx start/running, process 26505)output with :sudo /etc/init.d/nginx restartRestarting nginx nginx [fail]6)output with:tail -f /var/log/nginx/error.log> 2015/12/26 15:35:23 [notice] 2088#2088: signal process started
2015/12/26 15:45:23 [notice] 2266#2266: signal process started
2015/12/26 15:45:23 [alert] 2095#2095: *9 open socket #3 left in connection 5
2015/12/26 15:45:23 [alert] 2095#2095: aborting
2015/12/26 15:49:02 [alert] 2303#2303: *1 open socket #3 left in connection 3
2015/12/26 15:49:02 [alert] 2303#2303: aborting
2015/12/26 16:00:39 [notice] 2475#2475: signal process started
2015/12/26 16:02:25 [notice] 2525#2525: signal process started
2015/12/26 16:03:08 [notice] 2565#2565: signal process started
2015/12/26 16:14:45 [notice] 2645#2645: signal process started`
I am just having bad time with this 502 Bad Gateway> nginx/1.9.7and php> PHP 7.0.1-1+deb.sury.org~trusty+2 (cli) ( NTS )`
If anyone can please help me move on with this situation, that would be great. And, thank you in advance. | 502 Bad Gateway nginx (1.9.7) in Homestead [ Laravel 5 ] |
You probably still have the default.conf still in the directory that nginx is using to serve up the sites. either that or check in nginx.conf. Somewhere there is a server setup already using 80 that is being served first. | I am using a DigitalOcean VPS hosting a meteor app. I don't have a domain name yet, so just use the plain IP address. When I set below config and usemyipaddress:3000andmyipaddress:8080, both of them worked well; but if I change the 8080 to 80, onlymyipaddress:3000works. Using onlymyipaddressormyipaddress:80will show "Welcome to nginx on Debian!" message. (I use Ubuntu 14.04 on the VPS).server {
listen 8080;
server_name default;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}Can not figure out why can't use port 80.---- Solved this problem --------I commented out the "listen 80 default_server" in the /etc/nginx/sites-enabled/default" file, then my config at "/etc/nginx/conf.d/mysite.conf" works on port 80. | Nginx proxy_pass doesn't work on port 80 |
You could useGeo module. Your configuration then would look somewhat like this:geo $upstream {
default default_upstream;
10.50.0.0/16 some_upstream;
10.51.0.0/16 another_upstream;
}
upstream default_upstream {
server 192.168.0.1:80;
}
upstream some_upstream {
server 192.168.0.2:80;
}
upstream another_upstream {
server 192.168.0.3:80;
}
server {
...
location ... {
...
proxy_pass http://$upstream;
}
...
} | I've got a case where I need to do a different proxy pass in Nginx depending on which CIDR the client's IP address is part of.So, for example, let's say I have the following CIDRs:10.50.0.0/16
10.51.0.0/16
10.52.0.0/16Each of those client addresses needs to have a different proxy_pass in Nginx. How would I go about doing this? I'm very new to Nginx so achieving things like this are still a bit confusing. | Nginx - Different proxy pass based on IP ranges |
Ok, it's easy. Just set thecontent-type:if (!err) {
res.contentType('image/png');
res.send(tile);
} else {
res.send("Tile rendering error: " + err + "\n");
}These images are always.png.New headers:HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 01 Sep 2014 07:33:22 GMT
Content-Type: image/png
Content-Length: 37779
Connection: keep-alive
X-Powered-By: Express
ETag: W/"9393-1937584155" | Asimple serverI'm working can serve images. When browsing to the image URL directly, Chrome offers to download the image, rather than just showing it in the browser. Why is that? Presumably it is something in the headers?The relevant code is this:tilestore.getTile(req.param("z"), req.param("x"), req.param("y"), function(err, tile) {
if (!err) {
res.send(tile);
} else {
res.send("Tile rendering error: " + err + "\n");
}
});Do I need to add something to the headers? They are currently as follows:HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Mon, 01 Sep 2014 07:22:30 GMT
Content-Type: application/octet-stream
Content-Length: 37779
Connection: keep-alive
X-Powered-By: Express
ETag: W/"9393-1937584155" | Show image with Express, instead of downloading it |
You may need to look at the proxy timeout configs in nginx if using nginx as a proxy:http://www.nginxtips.com/504-gateway-time-out-using-nginx/http://wiki.nginx.org/HttpProxyModuleproxy_connect_timeout 60;
proxy_read_timeout 120;Apigee timeout defaults:Connect timeout - 60s -connect.timeout.millisRead timeout - 120s -io.timeout.millisFYI Apigee timeouts are also configurable (in milliseconds) within the TargetEndpoint connection:
5000
5000
http://www.google.com
Depending on how long the server takes to respond can determine your ideal timeout configurations. In this case, a read timeout of 45-60s might be ideal to provide some buffer in case cloudstack slows down more. | I have a nodejs program that connects to cloudstack apis. Creating a Virtual Machine on cloudstack takes almost 20 secs.The program works fine on my local nodejs installation and also on apigee cloud. However when I deploy the same on customer's OPDK, Nginx returns a 502 - Bad gateway.
This linkhttp://www.nginxtips.com/502-bad-gateway-using-nginx/recommends increasing the buffer and timeout sizes in nginx.confhttp {
...
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
...
}What is the recommended ideal value? What is it on Apigee cloud?Regards, Girish | Increase buffer timeout size on nginx |
You are passing the settings totornado.web.Application()instead oftornado.httpserver.HTTPServerTry this,settings = dict(
...
ssl_options = {
"certfile": os.path.join("certs/myserver.crt"),
"keyfile": os.path.join("certs/myserver.key"),
},
...
)
def main():
http_server = tornado.httpserver.HTTPServer(tornado.web.Application(handlers),
ssl_options = {
"certfile": os.path.join("certs/myserver.crt"),
"keyfile": os.path.join("certs/myserver.key"),
})
http_server.listen(443)
tornado.ioloop.IOLoop.instance().start()Update:settings = dict(
...
ssl_options = {
"certfile": os.path.join("certs/myserver.crt"),
"keyfile": os.path.join("certs/myserver.key"),
},
...
)
def main():
http_server = tornado.httpserver.HTTPServer(tornado.web.Application(handlers), **settings)
http_server.listen(443)
tornado.ioloop.IOLoop.instance().start() | I have a question about tornado SSL configuration. I wanna handle HTTPS protocol. I also read docs and stackoverflow same issues. I have a SSL certificate & key files. Code looks likesettings = dict(
...
ssl_options = {
"certfile": os.path.join("certs/myserver.crt"),
"keyfile": os.path.join("certs/myserver.key"),
},
...
)
def main():
http_server = tornado.httpserver.HTTPServer(tornado.web.Application(handlers,
**settings))
http_server.listen(443)
tornado.ioloop.IOLoop.instance().start()After I starting my app. I wanna access from browserhttps://mydomain.combut it is not working and nothing happened it gives unsuccess request error. What should I do? BTWhttp://mydomain.com:443is working. | Tornado SSL certs |
If the url does not belong to any paths that you registered viaapp.get(/...(or POST etc.) methods, Express sends the file if the static path is set and the path that you give belongs to some files path under static files directory. File sending is nothing more thanstreams, they do not block the event queue completely, they are just pushed to the queue and as chunks recieved, they are piped to the HTTP connection, so they happen on the background of your code. The reason of suggesting nginx is that it is more fit to that job, serving files and routing, and it is also written in C, and optimized for that job, where the NodeJS is a more general-purpose tool compared to Nginx. | I thought serving static files (html, mov, css, jpg, etc.) with Express was going to require some hacks in nginx.But it seems that static files "just work" with Express. No special thing is required.How does Express static file serving really work?Why do some people advocate using nginx for static files? There must be a good reason for this. (Example:https://gist.github.com/joemccann/644282)Also, while a static file is downloading, does the Node.js event queue get blocked? I suppose not, but why not? | Express.js (Node.js): How does static file serving really work? |
You will need to build your Java service in its own app server -- Tomcat would be a good choice for this. From there, it's a simple matter of configuringnginxto act as a proxy to Tomcat. Yournginxconfiguration will look something like the following:user www-data;
worker_processes 4;
pid /var/run/nginx.pid;
events {
worker_connections 4096;
# multi_accept on;
}
http {
server {
listen 80; #incoming port for nginx
server_name localhost;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
#...and other things, like basic settings, logging, mail, etc.The important piece here is the setting forproxy_pass. That's tellingnginxto accept requests on port 80 and redirect them to port 8080 (Tomcat's standard port). | I am a really beginner on this topic, I need some helpful articles and your guidance.
I want to buildRESTFulAPI web service. As a http server chosennginx. But I don't know (couldnt find any article) anything about how I can redirect my query to my java module, which handles request and gives back inJSONtonginx. If my thoughts on type of back-end is not correct please help me to figure out on this... | How to connect nginx to my java module |
location ^~ /assets/should belocation ~ ^/assets/.The former isdoes not match /assets/, the latter ismatches a pattern that starts with /assets/Update your nginx config to get caching and pre-gzipped file serving working again. | I deployed a Rails 3.2.8 application via Capistrano, with asset pipeline enabled, to my Linode server.It is running nginx + unicorn.When I visit my application, the minimised JS and CSS are not being served, although the assets are present in/public/assets.$ tree assets
assets
|-- application-66e477d6fd8cf088e8be44affeead089.css
|-- application-66e477d6fd8cf088e8be44affeead089.css.gz
|-- application-7d3ead38a0b5e276a97d48e52044ac31.js
|-- application-7d3ead38a0b5e276a97d48e52044ac31.js.gzIn my application, I can see those exact files not being found:This is my nginx configuration:server {
listen 80 default deferred;
server_name me.example.com;
root /home/kennym/apps/app/current/public;
location ^~ /assets/ {
add_header Last-Modified "";
add_header ETag "";
gzip_static on;
expires max;
add_header Cache-Control public;
}
try_files $uri/index.html $uri @unicorn;
location @unicorn {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://unicorn;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}Can you guess what is wrong? | Rails/Nginx not serving JS and CSS |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.