I have a Django application, and I'm using a shared server hosting, so I cannot change apache's config files. The only thing that I can change is the .htaccess file in my application. I also have a standard django.wsgi python file, as an entry point.
In dev environment, I'm using Django to serve the static files, but it is discouraged in the official documentation, saying that you should do it using the web server instead.
Is there a way to serve static files through apache without having access to Apache's configuration开发者_如何学Go, changing only the .htaccess or django.wsgi files??
The first step is to add just
AddHandler wsgi-script .wsgi
to your .htaccess file with nothing else to establish wsgi as the handler. This will make requests to django.wsgi and django.wsgi/whatever go to your django app.
To make the django.wsgi part of the URL go away, you will need to use mod_rewrite. Hopefully your host has it enabled. An example is
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /django.wsgi/$1 [QSA,PT,L]
which will serve the file if the URL matches a file, or be served by django if it doesn't. Another option would be
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^/?static/
RewriteRule ^(.*)$ /django.wsgi/$1 [QSA,PT,L]
to make requests for /static/* go to the file itself and everything else to go through django.
Then you will need to hide django.wsgi from generated URLs. This can be done with a snippet like this in your django.wsgi
def _application(environ, start_response):
# The original application.
...
import posixpath
def application(environ, start_response):
# Wrapper to set SCRIPT_NAME to actual mount point.
environ['SCRIPT_NAME'] = posixpath.dirname(environ['SCRIPT_NAME'])
if environ['SCRIPT_NAME'] == '/':
environ['SCRIPT_NAME'] = ''
return _application(environ, start_response)
If this doesn't work out quite exactly right, then be sure to consult http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines. I pulled most of the details of the answer from there but just got the right parts put together as a step by step.
Serve the static files from a different virtual host.
精彩评论