已安装WordPress的域名下安全运行独立PHP代码的方法
Absolutely, you can safely access your unrelated random-names.php file even when WordPress is installed on your domain. The core issue here is WordPress's default .htaccess rewrite rules, which route most requests to index.php—but we can adjust this to make exceptions for your standalone file. Here are two reliable, secure methods:
Method 1: Modify Your .htaccess File
WordPress uses mod_rewrite rules to manage permalinks, which is why direct access to non-WP files gets blocked by default. Here's how to update your root .htaccess to whitelist random-names.php:
- Open your root
.htaccessfile (it’s in the same directory aswp-settings.phpandwp-signup.php). - Locate the
# BEGIN WordPressblock. Add a new rewrite rule right after theRewriteRule ^index\.php$ - [L]line, like this:# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # Allow direct access to random-names.php RewriteRule ^random-names\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress - Save the file. The new rule tells the server: "If the request is for
random-names.php, handle it directly and stop processing further rewrite rules."
Method 2: Use a Separate Subdirectory
If you’d rather not edit .htaccess, you can place random-names.php in a new subdirectory (e.g., /standalone/) in your domain’s root. WordPress’s default rewrite rules only route requests to index.php if the requested file or directory doesn’t exist. Since the subdirectory is real, requests to yourdomain.com/standalone/random-names.php will bypass WordPress entirely.
Important Security Tips
- Audit your standalone file: Make sure
random-names.phphas no security flaws (like unfiltered user input, exposed credentials, or insecure file operations)—WordPress’s security measures won’t protect this independent file. - Avoid WP core directories: Never place standalone files in
wp-content,wp-admin, orwp-includes—these directories have their own access restrictions and mixing unrelated code here can cause conflicts or expose vulnerabilities. - Clear cache if needed: If you use a caching plugin (e.g., WP Rocket, W3 Total Cache), clear your site cache after making
.htaccesschanges to ensure the new rules take effect immediately.
内容的提问来源于stack exchange,提问作者Vineet Sharma

