You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构建URL Router?实现脚本的友好URL路径访问

How to Set Up a Friendly URL Router (Replace Clunky CGI Paths)

Great question! Ditching awkward paths like https://www.example.com/cgi-bin/test.py for clean, user-friendly URLs such as https://www.example.com/something/otherthing/test is a standard practice that boosts usability and SEO. Let’s break this down into actionable steps based on your setup:

1. Server-Side Rewrite Rules (Apache or Nginx)

Most of the time, you’ll leverage your web server’s built-in rewrite tools to map friendly URLs to your CGI script. This is the simplest approach for basic setups.

Apache (Using mod_rewrite)

First, confirm mod_rewrite is enabled on your Apache server. Then create a .htaccess file in your site’s root directory with these rules:

RewriteEngine On

# Skip rewrite for real files/directories (like CSS, JS, images)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Map all friendly URLs to your CGI script, passing the path as context
RewriteRule ^(.*)$ /cgi-bin/test.py/$1 [L]
  • The RewriteCond lines ensure we don’t interfere with requests for actual assets (so your static files still load normally).
  • The RewriteRule takes any requested path (like /something/otherthing/test) and sends it to your CGI script as a PATH_INFO value (we’ll use this in the next step).

Nginx

In your Nginx server configuration file, add this block inside the server directive:

location / {
    # Check for real files/directories first
    try_files $uri $uri/ @cgi_router;
}

location @cgi_router {
    # Pass the full friendly path to your CGI script
    fastcgi_pass unix:/var/run/cgi.sock; # Or use a TCP port like 127.0.0.1:9000
    fastcgi_param SCRIPT_FILENAME /path/to/your/cgi-bin/test.py;
    fastcgi_param PATH_INFO $request_uri;
    include fastcgi_params;
}

If you’re using Nginx’s older CGI module instead of FastCGI, replace fastcgi_pass with cgi_pass.

2. Handle Routing in Your Python CGI Script

Once the server maps the friendly URL to your script, you need to parse the incoming path and route the request to the right logic. Here’s a straightforward example for your test.py script:

#!/usr/bin/env python3
import os
from urllib.parse import unquote

# Define your route handler functions
def handle_test_endpoint():
    print("Content-Type: text/html")
    print()
    print("<h1>Welcome to the Test Endpoint!</h1>")
    print(f"<p>You accessed: {os.environ.get('PATH_INFO')}</p>")

def handle_home():
    print("Content-Type: text/html")
    print()
    print("<h1>Home Page</h1>")

def handle_404():
    print("Content-Type: text/html")
    print("Status: 404 Not Found")
    print()
    print("<h1>404 - Page Not Found</h1>")

def main():
    # Get the decoded friendly path from the server
    requested_path = unquote(os.environ.get('PATH_INFO', '/'))
    
    # Map paths to their corresponding handlers
    route_map = {
        '/': handle_home,
        '/something/otherthing/test': handle_test_endpoint,
        # Add more routes here as your app grows
    }
    
    # Run the matching handler, or 404 if no match exists
    handler = route_map.get(requested_path, handle_404)
    handler()

if __name__ == '__main__':
    main()
  • PATH_INFO is an environment variable set by the server that contains the friendly path trailing your script.
  • unquote() ensures we correctly handle encoded characters (like %20 for spaces) in the URL.

3. Bonus: Use a Python Web Framework (For Larger Projects)

If you’re building a more complex app, lightweight frameworks like Flask or Bottle handle routing out of the box—no server rewrite rules needed (beyond pointing the server to the framework’s WSGI entry point). For example, in Flask:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "<h1>Home Page</h1>"

@app.route('/something/otherthing/test')
def test_endpoint():
    return "<h1>Test Endpoint!</h1>"

if __name__ == '__main__':
    app.run()

Frameworks abstract away low-level CGI handling and make routing much more scalable as your app grows.


内容的提问来源于stack exchange,提问作者user7111260

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:51:38