如何为含用户插入外链的网站配置URL重写?求类脸书/推特方案
Great question—let’s break this down, fix the immediate link issue, and align your setup with how big platforms like Facebook/Twitter handle routing and external links.
First, the core problem: when users insert links like google.com instead of https://google.com, your browser treats it as a relative path (e.g., yourdomain.com/google.com). This gets caught by your .htaccess rule and forwarded to index.php, and since your routing logic doesn’t recognize this path, it falls back to loading the homepage instead of letting the browser jump to the external site.
Plus, your current setup has scalability gaps—let’s fix both the immediate problem and build a more robust foundation.
Is Your Current Setup "Reasonable"?
For a tiny prototype, sure—it works for basic routing. But it’s not sustainable long-term:
- It forwards all requests (including static files like CSS/JS/images) to
index.php, wasting server resources. - It lacks proper error handling (any unrecognized path loads the homepage, which is confusing for users and bad for SEO).
- It doesn’t account for how browsers handle relative vs. absolute URLs, which is why your external links are breaking.
Step 1: Fix the External Link Problem Immediately
The root fix here is ensuring user-inserted links are absolute URLs with a protocol (http/https). Most WYSIWYG editors (like TinyMCE, CKEditor) have built-in settings to enforce this:
Example TinyMCE Configuration
tinymce.init({ selector: '#your-editor', // Force absolute URLs with full protocol relative_urls: false, remove_script_host: false, convert_urls: true, // Optional: Add link validation to catch broken links link_checker: true });
This way, when a user types google.com, the editor automatically converts it to https://google.com. The browser will recognize this as an external link and jump directly to it—no detour through your server.
Step 2: Optimize Your .htaccess
Your current FallbackResource rule forwards every request to index.php, including static assets. Let’s adjust it to only forward non-existent files/directories:
# Skip existing files/directories (static assets like CSS/JS/images) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Forward all other requests to index.php FallbackResource index.php
This reduces unnecessary server load and ensures static resources load normally without being routed through index.php.
Step 3: Improve Your PHP Routing Logic
Your current explode($_SERVER['REQUEST_URI']) approach is fragile (it breaks if there are query parameters, or if your site is in a subdirectory). Let’s clean this up:
// Get the clean path (strip out query strings) $requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // Split into segments, removing leading/trailing slashes $pathSegments = explode('/', trim($requestPath, '/')); // If your site is in a subdirectory (e.g., /tests), strip that first segment $baseDirectory = 'tests'; if (!empty($pathSegments) && $pathSegments[0] === $baseDirectory) { array_shift($pathSegments); } // Handle routing with proper error handling if (!empty($pathSegments)) { switch($pathSegments[0]) { case 'notifications': require_once 'notifications.php'; break; // Add other internal routes here (e.g., 'profile', 'posts') // case 'profile': // require_once 'profile.php'; // break; default: // Return a proper 404 for unrecognized internal paths http_response_code(404); require_once '404.php'; break; } } else { // Load homepage for root requests require_once 'home.php'; }
This setup:
- Handles subdirectory hosting correctly
- Ignores query parameters that might clutter your route logic
- Returns a proper 404 page for invalid internal paths (instead of the homepage)
How Facebook/Twitter Do It (Long-Term Architecture)
If you want to scale like the big platforms, here’s their playbook:
1. Frontend-First Routing
They use client-side routing (e.g., React Router, Vue Router) where the frontend handles page navigation. Only API requests (like fetching notifications) go to the backend. External links are handled directly by the browser—no server-side forwarding needed.
2. Strict Link Validation
When users post content with links, the platform automatically:
- Checks if the link has a protocol (adds
https://if missing) - Validates the link is not malicious
- Stores the full absolute URL in the database
3. Backend API Only
The backend doesn’t serve HTML pages—it only provides JSON APIs for data. This separates concerns: frontend handles UI/navigation, backend handles data storage/processing.
4. Static Assets on CDN
All static files (images, CSS, JS) are hosted on a CDN, so they never touch the application server. This improves performance and reduces server load.
Final Takeaway
Your current setup works for testing, but to fix the external link issue and scale, focus on:
- Enforcing absolute URLs in your WYSIWYG editor
- Optimizing
.htaccessto skip static assets - Cleaning up your PHP routing logic with proper error handling
- For long-term growth, consider moving to a frontend-first, API-driven architecture like Facebook/Twitter use.
内容的提问来源于stack exchange,提问作者Nomore Mudzvova

