如何将React.js项目部署至cPanel?
Hey there! Let's work through getting your React project up on cPanel—this is totally fixable once we cover the common gotchas. Here's a step-by-step breakdown to troubleshoot and resolve your upload issues:
First off, you can't just upload your React project's source files (the ones with src/, package.json, etc.) directly to cPanel. React needs to be compiled into static HTML/CSS/JS files that browsers can read.
Run this command in your project's local terminal to generate the production build:
npm run build
This creates a build/ folder in your project root. You need to upload all the contents inside this folder (not the folder itself) to cPanel.
cPanel's default website root is the public_html folder. If you're deploying to your main domain, upload all the build files directly into public_html. For subdomains or addon domains, navigate to their corresponding root directory (e.g., public_html/your-subdomain) instead.
Pro tip: Using an FTP tool like FileZilla is often more reliable than cPanel's built-in file manager for large uploads, especially if you've had interruptions before.
.htaccess File React's single-page app routing can cause 404 errors when users refresh pages or navigate directly to URLs. To fix this, create a .htaccess file in your cPanel root directory (same place as your index.html) with these rules:
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
If you already have a .htaccess file (for things like redirects or SSL), just append these rules to the bottom—don't overwrite the existing content unless you know what you're doing.
Incorrect permissions can lead to 500 errors or blank pages. In cPanel's file manager:
- Set all files (like
.html,.js,.css) to permission644 - Set all folders (like
static/) to permission755
You can select all files/folders at once, right-click, and choose "Change Permissions" to bulk update these settings.
- Uploads keep failing: If cPanel's file manager throws size limits, switch to FTP or ask your host to increase the upload limit temporarily.
- Blank page when visiting your site: Open your browser's developer tools (F12) and check the Console tab—you'll likely see errors about missing assets. Double-check that you uploaded all files from the
build/folder, and if you set ahomepagefield in yourpackage.json, make sure it matches your cPanel domain path. - 500 Internal Server Error: This is almost always a
.htaccesssyntax issue or permission problem. Try temporarily renaming.htaccessto.htaccess-old—if the site loads, you know the routing rules were the culprit.
If you're still stuck, share any specific error messages you're seeing (from cPanel, your browser console, or upload logs) and we can narrow it down further!
内容的提问来源于stack exchange,提问作者user6305542

