ProxyPass and ProxyPassReverse for Django app - django

I have a follow up question from my original Django serving question which was how to develop Django apps and serve them from the same server as my main PHP-based site (all part of a larger migration of my website from a static and PHP driven one to a series of Django apps).
I couldn't quite use the name server solution I was provided with, and instead just deployed my Django applications on a different port (8000) using mod_wsgi. Now, however, I need to actually integrate the Django application into the main site. In my Apache 2.0 configuration file (for say http://www.example.com) I added the following ProxyPass commands (after my mod_wsgi initialization):
ProxyPass /app/newsletter http://www.example.com:8000/app/newsletter
ProxyPassReverse /app/newsletter http://www.example.com:8000/app/newsletter
Here I expect that any request to:
http://www.example.com/app/newsletter
will get successfully proxied to:
http://www.example.com:8000/app/newsletter
and all will be right with the world.
However, this is not the case. Apache hangs for 5 or so minutes (the time taken to craft this question) then spits out a 502 Proxy Error:
Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /app/newsletter/.
Reason: Error reading from remote server
Watching my Apache 2.0 error log after this response I see continuous errors like the following:
[Thu Sep 27 15:25:49 2012] [error] Exception KeyError: KeyError(****,) in <module 'threading' from '/usr/lib64/python2.6/threading.pyc'> ignored
So something seems to be remiss in either how mod_proxy plays with Django and/or Python. I have other Java related processes that I use ProxyPass and ProxyPassReverse on and they work fine. Also, when I don't try to apply the ProxyPass the Django apps all work well (ie. when I address them on port 8000 directly).
Any ideas? I don't feel like what I am doing is particularly complex.
Thanks in advance.

In the end, using mod_rewrite was the solution. Added this to Apache's httpd.conf file:
RewriteEngine On
RewriteRule ^/app/newsletter/(.*)$ http://%{SERVER_NAME}:8000%{REQUEST_URI} [P]
Everything works as expected.

Related

XAMPP with WSGI not rendering django page

I am trying to run django on XAMPP Apache server and followed the steps mentioned here. Here are the changes in Apache config:[![enter image description here][1]][1]
When access the application in browser below is the result instead of django page:
[![enter image description here][2]][2]
Please help what I am missing in this ?
#Razenstein: Following are errors in Apache log:
AH02102: C:/xampp/htdocs/polls/mysite/mysite/wsgi.py is not executable; ensure interpreted scripts have "#!" or "'!" first line (9)Bad file descriptor: [client 127.0.0.1:58357] AH01222: don't know how to spawn child process: C:/xampp/htdocs/polls/mysite/mysite/wsgi.py
The application is running fine with built in python server. After correcting Alias getting "500 | Internal Server Error"
[1]: https://i.stack.imgur.com/w2R0Y.png
[2]: https://i.stack.imgur.com/vl8Da.png
ok, this error message says that Apache tries to execute wsgi.py as a cgi script and not as python. A possible reason is, that you tried to deploy your app on Apache with some wrong commands that are still in the httpd.conf or vhosts-httpd.conf. This typically happens if you follow one (bad?) tutorial without success, switch to another one and forgot to clean the the code from the first trial (only a guess!). There is all kinds of strange turorials out there and sometimes it is also difficult to understand if they are for Windows or Unix.
Something like the follwing would cause that behavior:
Alias / C:/xampp/htdocs/polls/mysite/mysite/wsgi.py
<Directory C:/xampp/htdocs/polls/mysite/mysite>
Options +ExecCGI
AddHandler cgi-script .cgi .pl .asp .py
Require all granted
</Directory>
please search in your httpd.conf and vhosts-httpd.conf if you have left something similar.
your "WSGIScriptAlias ...." is overwritten by that and not active.

How to configure uWSGI to use ssl-socket instead of socket

I have an Apache reverse proxy server with a config:
ProxyPass /hub06/ uwsgi://myotherserver:8006/
ProxyPassReverse /hub06/ uwsgi://myotherserver:8006/
Then I have a second server running a Django app with uwsgi setup like this:
ssl-socket=0.0.0.0:8006,/home/user1/server.crt,/home/user1/server.key,HIGH
I am getting internal server error. When I use a plain socket without a certificate:
socket=0.0.0.0:8006
It works perfectly well.
Any ideas how to make ssl-socket work please?
mod_proxy_uwsgi does not currently support uwsgi over ssl (albeit it should be an easy addition). If you need ssl for backends, you may want to use https-socket (instead of ssl-socket) and mod_proxy_http

Running apache bloodhound on apache2 web server

I am trying to run to apache bloodhound tracker on apache2 web server. I am using 0.7 version of the blood hound. I followed the website https://issues.apache.org/bloodhound/wiki/BloodhoundInstall
Blood hound is running on port 8000.
But the problem is I am not able to run the blood hound on port 80, so that if I hit bloodhound.mydomain.com, I should get bloodhound. I have mentioned my apache2 webserver setting file as specified in the website
/etc/apache2/sites-available/bloodhound
<VirtualHost *:8080>
WSGIDaemonProcess bh_tracker user=ubuntu python-path=/home/ubuntu/bloodhound-0.7/installer/bloodhound/lib/python2.7/site-packages
WSGIScriptAlias /bloodhound /home/ubuntu/bloodhound-0.7/installer/bloodhound/site/cgi-bin/trac.wsgi
<Directory /home/ubuntu/bloodhound-0.7/installer/bloodhound/site/cgi-bin>
WSGIProcessGroup bh_tracker
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
<LocationMatch "/bloodhound/[^/]+/login">
AuthType Digest
AuthName "ubuntu"
AuthDigestDomain /bloodhound
AuthUserFile /home/ubuntu/bloodhound-0.7/installer/bloodhound/environments/main/bloodhound.htdigest
Require valid-user
</LocationMatch>
</VirtualHost>
After adding the above file, its not running on either of the ports 8000 and also 8080 also.
How do I make it run. Kindly help me. By the way I am using ubuntu ec2 instance.
By golly I think I've figured it out! I've been stuck right about where you are on my own Bloodhound port configuration for days.
n3storm is correct: the whole magic of setting up mod_wsgi is that you no longer need to manually start bloodhound with that
tracd port=8080 /ridiculously/long/path/to/bloodhound/installer/bloodhound/environments/main
command. Instead, mod_wsgi runs all that python for you the moment your web browser requests http://[host]:8080/bloodhound, meaning your Bloodhound server is ready to serve the moment it's turned on.
The pain is how many interlocking config files are involved, and how many tiny things can break down the whole process. I don't really know python, I just barely understand Apache, and I'm 70% confident I've accidentally opened some gaping security that I don't understand, but here's my understanding of the mod_wsgi + Apache + Bloodhound domino chain. Paths are for my Apache 2.4 installation on Ubuntu 14.04.1 LTS:
1. You load http://[host]:8080/bloodhound
For this to work, I needed to edit /etc/apache2/ports.conf so that Apache is actually listening on port 8080. So add the line
Listen 8080
to /etc/apache2/ports.conf
Now visiting http://[host]:8080/bloodhound should at least show you something from Apache. For me, it was a HTTP Error 403: Forbidden page, and next up is my home remedy for the Error 403 blues!
2. Apache triggers bloodhound.conf
FULL PATH: /etc/apache2/sites-available/bloodhound.conf
Technically, Apache is looking in /etc/apache2/sites-enabled/ for a matching VirtualHost rule but you set this up by creating/editing .conf files in /sites-availabe/ and then activating them with the Apache command
a2ensite [sitename].conf
So. Apparently, Apache 2.4 changed its access control syntax for .conf files. So, to stop the Error 403ing, I changed
Order deny,allow
Allow from all
in /etc/apache2/sites-available/bloodhound.conf to
Require all granted
And then once again you should restart Apache with
sudo apachectl graceful
or
sudo /etc/init.d/apache2 graceful
or maybe
sudo service apache2 restart
I'm not sure, they all seem to work equally but I suppose the graceful ones are nice because they don't shut down your server or something important like that.
3. bloodhound.conf triggers trac.wsgi
FULL PATH: /ridiculously/long/path/to/bloodhound/installer/bloodhound/site/cgi-bin/trac.wsgi
After figuring out that ton of other things, I realized that, in the end, the default script that Bloodhound generates worked fine for me:
import os
def application(environ, start_request):
if not 'trac.env_parent_dir' in environ:
environ.setdefault('trac.env_path', '/usr/local/bloodhound/installer/bloodhound/environments/main')
if 'PYTHON_EGG_CACHE' in environ:
os.environ['PYTHON_EGG_CACHE'] = environ['PYTHON_EGG_CACHE']
elif 'trac.env_path' in environ:
os.environ['PYTHON_EGG_CACHE'] = \
os.path.join(environ['trac.env_path'], '.egg-cache')
elif 'trac.env_parent_dir' in environ:
os.environ['PYTHON_EGG_CACHE'] = \
os.path.join(environ['trac.env_parent_dir'], '.egg-cache')
from trac.web.main import dispatch_request
return dispatch_request(environ, start_request)
4. trac.wsgi serves up the HTML files for Bloodhound
Isn't the internet just magical?
By using Apache mod_wsgi you don't need Bloodhound running apart anymore. Is mod_wsgi what makes Bloodhound running. You should use standard apache port in this case.
Also, I guess you should use a ServerName directive at Virtualhost (or is it you only serve one host?)

URLs redirection problems deploying a working django app in apache (via mod_wsgi)

I've a django app that works perfectly under the django development server. I'm trying to deploying it in apache2.2 using the mod_wsgi and I have errors.
In the httpd.conf file I "mounted" my app under the root /myapp using:
WSGIScriptAlias /myapp /home/path_to_my_app/apache_conf/django.wsgi
I've followed the standard indication to prepare django.wsgi. Now, I can reach the main page template of my app but it seems to have redirection errors. The "/myapp" root is not inserted automatically on ULRs redirection requests. Request from the main page template to some modules in views.py via urls.py cannot be correctly delivered.
apache error log:
127.0.0.1 - - [21/Feb/2011:16:11:44 +0100] "GET /myapp/ HTTP/1.1" 200 1795
127.0.0.1 - - [21/Feb/2011:16:11:46 +0100] "GET /api/dir HTTP/1.1" 404 205
"/api/dir" doesn't exist, it should be matched from a pattern in urls.py, but id doesn't
I've spent more than 2 days with it, please can somebody help?
It appears you are missing some things from your apache config:
In the working config for my server I have:
# tell apache where to find the wsgi script.
WSGIScriptAlias / "/home/path_to_my_app/wsgi/my.settings.wsgi"
# turn on auto-reload in WSGI
WSGIScriptReloading On
WSGIReloadMechanism Process
# assign a process to a process group
WSGIDaemonProcess djangoapps processes=10 threads=1 maximum-requests=500 display-name=my-wsgi
WSGIProcessGroup djangoapps
Your WSGIScriptAlias line is correct but you need to tell wsgi how you are going to run your application.
You are most likely getting 404's because there is not a WSGIDaemonProcess line to tell the WSGI handler how to work with your process.
http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives might be a helpful reference.
Finally I found the error. It was not connected to httpd.conf file but to how URLs are specified both to django urls.py file and to templates. As I mounted myapp in this way:
WSGIScriptAlias /myapp my_path_to_wsgi_module/django.wsgi
I was believing that URLs specified in django template files should carry an initial slash, like this:
'/api/dir'
It results that in this way the application works only on django development server but not on apache.
Instead if you use URLs without initial slash like:
'api/dir'
The app works correctly both on django development server and on apache!
You must avoid using starting slashes even on pattern matching of django urls.py file:
like this: (r'^api/dir$', 'available_services')
and NOT like this: (r'^/api/dir$', 'available_services')
Maybe this is an obvious thing for expert django users but if you're novice like me, this can make you loose a certain amount of time because it's a hard problem to be detected.
Actually it is a bit more complicated than just that.
There are some times when you need absolute in-app urls, because you don't want to reach an url which is relative to the current url.
e.g. you have a global menu in a main layout template (i.e. a template which is "extend"ed by each other template in your project): you cannot have relative urls like "home", "contact", "about", "blog" because if you are in /yourapp/blog/entries/2014/02/06/add (let's say such url exist) and you click any menu item, you would go to (say, for "home") /yourapp/blog/entries/2014/02/06/add/home instead to /home, which you would expect.
The ugly solution of virtual hosts is good here (in Java, Struts 2 has an option to resolve urls for "actions" (i.e. named urls / entry points) including the deploy context directory as deployed in the web container (e.g. tomcat)) ... don't know it there's any "context" setting you can guess (perhaps it's possible to return the current "WSGIScriptAlias" key as an environment variable). After that, using back the initial slash for urls ("/home").

C/C++ FastCGI Developers toolkit example program (not working?)

I am using the fastcgi C/C++ toolkit, to develop a test fastcgi app.
I built (and am now testing) this example provided by the toolkit.
I have loaded Apache mod_fcgid and successfully restarted the apache2 daemon. However, when I try to access the fastcgi resource, it is returning a blank page.
Note: I made the following changes to the example code (as it didn't work with the default socket fd value of 0):
int sock_fd = FCGX_OpenSocket(":5000", 1);
FCGX_InitRequest(&request, sock_fd, 0);
My /etc/apache2/mods-enabled/fcgid.conf file looks like this:
<IfModule mod_fcgid.c>
AddHandler fcgid-script .fcgi
SocketPath /var/lib/apache2/fcgid/sock
IPCConnectTimeout 10
IPCCommTimeout 20
OutputBufferSize 0
MaxRequestsPerProcess 500
</IfModule>
My /etc/apache2/mods-enabled/fcgid.load file looks like this:
LoadModule fcgid_module /my/path/here/libs/mod_fcgid.so
I then accessed the 'resource' in a browser using the following url:
http://127.0.0.1:5000
What am I doing wrong? (assuming that someone has actually managed to get the example cited above, to work)
I am developing/testing on Linux Ubuntu 10.x
i don't use apache for while, but i think your url is bad
i assume your apache run on port 80 and your echo.fcgi is at root of apache folder
for information, i use nginx for serve fcgi application
http://localhost/echo.fcgi
Run apachctl -D to verify your have mod_fcgid running. I believe no output (i.e a white page) occurs when your process crashes.
You will need to compile your program with debugging (-O0 -ggdb), redeploy, and restart Apache.
Change your Apache config to only spawn one process. This will allow you to attach gdb to your FCGI application and debug it.
Let me know if you need further assistance.