Apache shows Python code instead of execute it

VPS server running Ubuntu 22.04, Apache 2.4.18 and Python 3.5.2

When I try to access a webpage on that server it shows python code instead of execute it…

Last guide I tried was this: https://howtoforge.es/como-ejecutar-scripts-de-python-con-apache-y-mod-wsgi-en-ubuntu-20-04/

But the problem still remains.

Asked By: Art

||

Install wsgi

On Ubuntu 22.04 with Python 3, you have to install libapache2-mod-wsgi-py3:

sudo apt install libapache2-mod-wsgi-py3
sudo a2enmod wsgi
sudo service apache2 restart

Configure your vhost

Your manual mentions creating a new vhost config /etc/apache2/conf-available/wsgi.conf. However, this is not required and if you don’t have other sites on the server, you can use the default Apache config: /etc/apache2/conf-available/000-default.conf. Add the following line before the line:

WSGIScriptAlias ​​/wsgi /var/www/html/wsgy.py

Don’t forget to restart the Apache server:

sudo service apache2 restart

Create Python script

To configure mod_wsgi, you have to create a Python script that will be served by the Apache web server: sudo nano /var/www/html/wsgi.py. The example wsgi.py in your manual is returning error 500, so you can use this code instead:

def application(environ, start_response):
    status = '200 OK'
    output = b'Hello World!n'
    response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]

Accessing the Python site

  • To access the Python file, you should use http://your-server-ip/wsgi or whatever alias you configured in your vhost’s file.

  • Opening http://your-server-ip/wsgi.py will still return Python code instead of execute it.

Answered By: sotirov
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.