Broken URL rewriting on Django/modwsgi setup

I am trying to setup my Django app to run under Apache with modwsgi. I have defined the following virtualhost:

<VirtualHost *>
    ServerName www.domain.com
    ServerAlias domain.com

    WSGIScriptAlias / /home/domain/apache/django.wsgi

    <Directory /home/domain/apache>
    Order deny,allow
    Allow from all

    Options -Indexes +FollowSymlinks
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
    RewriteRule ^(.*)$ http://www.domain.com/$1 [QSA,L,R=301]
    </Directory>
</VirtualHost>

The rewrite rules at the end are there to make www.domain.com the canonical site name. There is something wrong though. When I browse to >http://domain.com, I get redirected to >http://www.domain.com/django.wsgi/. Browsing to >http://www.domain.com works just fine.

Am I missing something in my configuration? Thanks.

Update: I changed the RewriteRule to

RewriteRule ^django.wsgi/(.*)$ domain.com/$1 [L,R=301]. 

This change fixes the issue. I will appreciate it if someone can elaborate on why the /django.wsgi/ part ends up in the URL. Thanks!


Your original rewrite rule likely confused things because the $1 pattern that matched already had a '/' in it, thus you created a double slash. What happens if you use:

RewriteRule ^(.*)$ http://www.domain.com$1 [QSA,L,R=301]

and remove your extra rule?


UPDATE 1

You have misinterpreted what I meant. I wasn't talking about your workaround, but the original rule.

To make it more obvious what you are doing wrong and which is potentially causing issues, use:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^/(.*)$ http://www.domain.com/$1 [L,R=301]

Note how I have explicitly listed the '/' outside of the sub pattern. Only by doing that would it be okay to use a '/' before '$1'. If you don't you will get repeating slashes.

I'd also suggest dropping QSA. Examples I see elsewhere on the Internet don't use that either.

Finally, you should escape the '.' in the host name being matched else could technically match stuff other than a literal '.' as well.

So, try that. If still issues, then you should enable rewrite module logging and see what is going on. You possibly have some other rewrite rules in your configuration which are causing issues.


UPDATE 2

Hmmm, finally realised your actual problem is that you have the rewrite rule inside of the Directory directive container instead of outside.

So, move the rewrite rules to immediately inside of the VirtualHost and not the Directory directive.