如何在纯PHP中实现代理站点查询字符串转目录式URL?
Got it, let's walk through how to adjust your PHP proxy app to use clean directory-style URLs instead of query strings—all without touching .htaccess. Here's what you need to do:
Step 1: Parse the Request URI to Extract the Target URL
Since we can't rely on server rewrites, we'll have PHP directly read the incoming request URL and pull out the target proxy address from it. Add this code at the very top of your index.php file:
// Grab the full request path (e.g., "/search/https://example.com") $requestUri = rtrim($_SERVER['REQUEST_URI'], '/'); // Define your clean URL prefix (adjust this if you want a different path like "/proxy/") $cleanPrefix = '/search/'; // Check if the request matches our clean URL structure if (strpos($requestUri, $cleanPrefix) === 0) { // Extract the target URL by removing the prefix $targetUrl = substr($requestUri, strlen($cleanPrefix)); // Decode URL-encoded characters (critical for URLs with &, =, etc.) $targetUrl = urldecode($targetUrl); // Validate the target URL (add basic security checks here!) if (!filter_var($targetUrl, FILTER_VALIDATE_URL)) { die('Please enter a valid URL to proxy.'); } } else { // Handle backwards compatibility for old ?q=... links if (isset($_GET['q']) && !empty($_GET['q'])) { // Redirect old query string requests to the clean URL header("Location: {$cleanPrefix}" . urlencode($_GET['q'])); exit; } // Show a fallback if someone visits index.php directly echo '<h3>PHP Proxy</h3>'; echo '<p>Use the format: <code>yourdomain.com/search/https://example.com</code></p>'; exit; }
Step 2: Replace All References to $_GET['q']
Go through your existing proxy code and replace every instance of $_GET['q'] with the new $targetUrl variable we created above. For example, if your original code had something like:
$url = $_GET['q'];
Change it to:
$url = $targetUrl;
Key Notes & Security Tips
- URL Encoding/Decoding: We use
urlencode()when redirecting old requests to ensure special characters don't break the URL, andurldecode()to get the proper target URL from the clean path. - Security Validation: The
filter_var()check ensures users can't proxy invalid or malicious URLs (like local file paths). You might want to add more checks depending on your use case. - Server Compatibility: As long as
index.phpis set as your server's default document, requests to/search/...will still route toindex.phpautomatically—no rewrites needed. - Fallback Behavior: The code handles users visiting
index.phpdirectly by showing a simple instruction, which is better than throwing a confusing error.
That's it! Now users can access your proxy with URLs like yourdomain.com/search/https://example.com instead of the old query string format, and all the logic stays purely in PHP.
内容的提问来源于stack exchange,提问作者Shrey Gupta

