Laravel 5.6安装在子目录时,如何移除URL中的'public'?
Got it, let's tackle this step by step since your setup has WordPress in mainsite and Laravel in work under public_html, with the main domain already routing to mainsite. Here's how to remove the public segment from your Laravel app's URLs without messing up your main WordPress site:
1. Adjust Laravel's Core Files
First, we need to reconfigure Laravel to serve from its root work directory instead of the work/public subfolder:
- Copy the
.htaccessfile fromwork/public/to thework/directory (Laravel's root folder). - Open
work/index.phpand update the file paths to point correctly:// Replace these lines: require __DIR__.'/../vendor/autoload.php'; $app = require_once __DIR__.'/../bootstrap/app.php'; // With these: require __DIR__.'/vendor/autoload.php'; $app = require_once __DIR__.'/bootstrap/app.php'; - Update your Laravel config at
config/app.phpto set the correct base URL:
(Don't forget to update your'url' => env('APP_URL', 'https://www.example.com/work'),.envfile'sAPP_URLto match this too!)
2. Modify the Root public_html/.htaccess
Your existing .htaccess redirects all main domain traffic to mainsite, but we need to exclude requests to the work directory from that rule. Update your root .htaccess like this:
<IfModule mod_rewrite.c> RewriteEngine on # Skip main site redirect for Laravel's work directory RewriteCond %{REQUEST_URI} ^/work/ RewriteRule ^ - [L] # Original main site redirect rule RewriteCond %{HTTP_HOST} ^(www.)?example.com$ RewriteCond %{REQUEST_URI} !^/mainsite/ RewriteRule ^(.*)$ /mainsite/$1 [L] </IfModule>
The [L] flag ensures that once a request matches the /work/ rule, it stops processing further redirects.
3. Update the Laravel Root .htaccess
Now edit the .htaccess you copied to work/ earlier, replacing its content with this rule to route all traffic to the public subfolder silently:
<IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^(.*)$ public/$1 [L] </IfModule>
This will make any request to www.example.com/work/your-route internally map to work/public/your-route without showing public in the URL.
4. Quick Checks to Avoid Issues
- Permissions: Make sure Laravel's
storage/andbootstrap/cache/directories have write permissions for your web server user. - Apache Config: Verify that your server's Apache config has
AllowOverride Allenabled for yourpublic_htmldirectory—this lets.htaccessrules take effect. - Clear Caches: Flush your browser cache and run
php artisan cache:clear+php artisan config:clearin your Laravel directory to avoid stale configs.
That's it! Now you should be able to access your Laravel app at www.example.com/work without seeing the public segment in the URL, while your main domain still routes correctly to the WordPress site in mainsite.
内容的提问来源于stack exchange,提问作者Saurabh Borse

