本文详解2026年Web3.0去中心化网站架构,包括IPFS、Blockchain、ENS等技术实战。

什么是Web3.0

Web3.0(2026年定义):

  • 去中心化(Decentralized)
  • 用户拥有数据(User-Owned Data)
  • 无需信任(Trustless)
  • 代币激励(Token Incentives)

vs Web2.0:

  • Web2.0:数据存储在中心化服务器(Google/Facebook)
  • Web3.0:数据存储在分布式网络(IPFS/Arweave)

去中心化网站技术栈

存储层:

  • IPFS(InterPlanetary File System)- 分布式文件存储
  • Arweave - 永久存储(一次付费,永久存储)
  • Filecoin - IPFS的激励层(存储挖矿)

域名层:

  • ENS(Ethereum Name Service)- 以太坊域名
  • Unstoppable Domains - 去中心化域名

前端层:

  • Next.js/React(传统前端框架)
  • Web3-React(集成钱包登录)

智能合约层:

  • Solidity(以太坊智能合约)
  • Rust(Solana/Solidity替代)

实战一:使用IPFS托管网站

安装IPFS

# 方法一:IPFS Desktop(图形界面)

访问 https://github.com/ipfs/ipfs-desktop/releases

下载并安装

方法二:IPFS CLI

Linux/macOS

wget https://dist.ipfs.tech/kubo/v0.25.0/kubo_v0.25.0_linux-amd64.tar.gz

tar -xzf kubo_v0.25.0_linux-amd64.tar.gz

cd kubo

sudo ./install.sh

验证

ipfs --version

初始化并启动IPFS节点

# 初始化IPFS配置

ipfs init

启动IPFS守护进程(Daemon)

ipfs daemon

输出示例:

WebUI: http://127.0.0.1:5001/webui

Gateway: http://127.0.0.1:8080/ipfs/

API: /ip4/127.0.0.1/tcp/5001

上传网站到IPFS

# 1. 构建静态网站(以Next.js为例)

cd my-website

npm run build

npm run export # 输出:out/ 目录

2. 上传到IPFS

ipfs add -r out/

输出示例:

added Qm... out/index.html

added Qm... out/_next/...

...

网站CID(Content Identifier):QmXYZ...

3. 访问网站(通过本地网关)

http://127.0.0.1:8080/ipfs/QmXYZ...

4. 固定(Pin)到IPFS(防止垃圾回收)

ipfs pin add /ipfs/QmXYZ...

实战二:使用Pinata(IPFS固定服务)

注册Pinata

1.  访问 https://www.pinata.cloud/

  • 注册账号
  • 获取API Key(Settings → API Keys → New Key)

上传到Pinata(API)

// upload-to-pinata.js

const axios = require('axios');

const fs = require('fs');

const FormData = require('form-data');

const PINATA_API_KEY = 'YOUR_API_KEY';

const PINATA_SECRET_API_KEY = 'YOUR_SECRET_API_KEY';

async function uploadToPinata(filePath) {

const formData = new FormData();

formData.append('file', fs.createReadStream(filePath));

const response = await axios.post(

'https://api.pinata.cloud/pinning/pinFileToIPFS',

formData,

{

headers: {

'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,

'pinata_api_key': PINATA_API_KEY,

'pinata_secret_api_key': PINATA_SECRET_API_KEY,

},

}

);

console.log('IPFS CID:', response.data.IpfsHash);

// 访问:https://gateway.pinata.cloud/ipfs/

}

uploadToPinata('./out/index.html');

上传整个目录

// upload-directory-to-pinata.js

const axios = require('axios');

const fs = require('fs');

const path = require('path');

async function uploadDirectoryToPinata(directoryPath) {

const formData = new FormData();

// 遍历目录,添加所有文件

function addFiles(dir, basePath = '') {

const files = fs.readdirSync(dir);

for (const file of files) {

const fullPath = path.join(dir, file);

const relativePath = path.join(basePath, file);

if (fs.statSync(fullPath).isDirectory()) {

addFiles(fullPath, relativePath);

} else {

formData.append('file', fs.createReadStream(fullPath), relativePath);

}

}

}

addFiles(directoryPath);

const response = await axios.post(

'https://api.pinata.cloud/pinning/pinFileToIPFS',

formData,

{

headers: {

'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,

'pinata_api_key': PINATA_API_KEY,

'pinata_secret_api_key': PINATA_SECRET_API_KEY,

},

maxContentLength: Infinity,

maxBodyLength: Infinity,

}

);

console.log('Directory CID:', response.data.IpfsHash);

}

uploadDirectoryToPinata('./out');

实战三:使用ENS(以太坊域名服务)

注册ENS域名

1.  访问 https://app.ens.domains/

  • 搜索可用域名(如:mywebsite.eth)
  • 注册(需要支付ETH Gas费)
  • 设置解析记录(Resolver Record)

将ENS域名指向IPFS网站

1.  登录ENS管理界面(https://app.ens.domains/name/mywebsite.eth)

  • 点击"Records" → "Add/Edit Record"
  • 选择"Content" → 输入IPFS CID(如:ipfs://QmXYZ...)
  • 保存(需要支付Gas费)
  • 等待确认(1-3分钟)

现在访问:https://mywebsite.eth.link (自动解析到IPFS)

使用ENS.js(前端解析ENS)

// 安装ethers.js

npm install ethers

// resolve-ens.js

const { ethers } = require('ethers');

async function resolveENS(ensName) {

// 连接到以太坊主网(使用Infura或Alchemy RPC)

const provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_KEY');

// 解析ENS到IPFS CID

const resolver = await provider.getResolver(ensName);

const content = await resolver.getContent();

console.log('IPFS CID:', content.hash);

// 访问:https://gateway.pinata.cloud/ipfs/

}

resolveENS('mywebsite.eth');

实战四:使用Web3-React(集成钱包登录)

安装Web3-React

npm install @web3-react/core @web3-react/metamask @web3-react/walletconnect

配置Web3-React

// web3-react.ts

import { initializeConnector, Web3ReactHooks } from '@web3-react/core';

import { MetaMask } from '@web3-react/metamask';

import { WalletConnect } from '@web3-react/walletconnect';

const [metaMask, metaMaskHooks] = initializeConnector(

(actions) => new MetaMask({ actions })

);

const [walletConnect, walletConnectHooks] = initializeConnector(

(actions) => new WalletConnect({

actions,

options: {

rpc: {

1: 'https://mainnet.infura.io/v3/YOUR_INFURA_KEY',

},

},

})

);

export const connectors = [metaMask, walletConnect];

export const hooks = [metaMaskHooks, walletConnectHooks];

使用Web3-React登录

// components/ConnectButton.tsx

'use client';

import { connectors, hooks } from '@/lib/web3-react';

export default function ConnectButton() {

const { useIsActive, useAccount } = hooks[0]; // MetaMask hooks

const isActive = useIsActive();

const account = useAccount();

const connect = () => {

connectors[0].activate(); // 激活MetaMask

};

const disconnect = () => {

connectors[0].deactivate(); // 断开连接

};

if (isActive) {

return (

已连接:{account}

);

}

return ;

}

实战五:部署智能合约(存储网站数据)

编写智能合约(Solidity)

// contracts/WebsiteStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

contract WebsiteStorage {

struct Page {

string title;

string contentCID; // IPFS CID

address author;

uint256 timestamp;

}

mapping(uint256 => Page) public pages;

uint256 public pageCount = 0;

event PageCreated(uint256 id, string title, address author);

function createPage(string memory title, string memory contentCID) public {

pages[pageCount] = Page({

title: title,

contentCID: contentCID,

author: msg.sender,

timestamp: block.timestamp

});

emit PageCreated(pageCount, title, msg.sender);

pageCount++;

}

function getPage(uint256 id) public view returns (

string memory title,

string memory contentCID,

address author,

uint256 timestamp

) {

Page memory page = pages[id];

return (page.title, page.contentCID, page.author, page.timestamp);

}

}

部署智能合约(Hardhat)

# 安装Hardhat

npm install -D hardhat @nomicfoundation/hardhat-toolbox

初始化Hardhat项目

npx hardhat init

编译合约

npx hardhat compile

部署到以太坊测试网(Goerli)

npx hardhat run scripts/deploy.js --network goerli

// scripts/deploy.js

async function main() {

const [deployer] = await ethers.getSigners();

console.log('Deploying with account:', deployer.address);

const WebsiteStorage = await ethers.getContractFactory('WebsiteStorage');

const contract = await WebsiteStorage.deploy();

console.log('WebsiteStorage deployed to:', await contract.getAddress());

}

main().catch((error) => {

console.error(error);

process.exitCode = 1;

});

去中心化网站性能优化

优化一:使用IPFS网关集群(Gateway Cluster)

// 使用多个公共网关( fallback)

const gateways = [

'https://gateway.pinata.cloud',

'https://cloudflare-ipfs.com',

'https://ipfs.io',

];

async function fetchFromIPFS(cid) {

for (const gateway of gateways) {

try {

const response = await fetch(`${gateway}/ipfs/${cid}`);

if (response.ok) {

return await response.text();

}

} catch (error) {

console.log(`Gateway ${gateway} failed, trying next...`);

}

}

throw new Error('All gateways failed');

}

优化二:使用IPNS(可变指针)

# IPNS(InterPlanetary Name System):

- 允许更新内容(CID可变)

- 类似DNS(域名不变,IP可变)

1. 发布到IPNS(关联密钥对与CID)

ipfs name publish /ipfs/QmXYZ...

2. 访问(通过IPNS)

https://gateway.pinata.cloud/ipns/

3. 更新内容(重新发布)

ipfs name publish /ipfs/QmNEW...

决策建议

| 场景 | 是否使用Web3.0 | 理由 |

|------|------------------|------|

| 内容审查敏感网站 | ✅ 强烈推荐 | 去中心化,无法审查 |

| 需要用户数据主权 | ✅ 推荐 | 用户拥有数据 |

| 普通企业官网 | ❌ 不推荐 | 中心化服务器更便宜 |

| 高流量电商 | ❌ 不推荐 | 性能不如CDN |

总结

Web3.0去中心化网站是2026年最前沿的网站架构。虽然性能与用户体验还不如Web2.0,但在抗审查、数据主权方面有独特优势。

立即行动:用IPFS + Pinata托管你的第一个去中心化网站!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。