网站/WordPress从虚拟主机搬家到VPS上

拖了一个月终于着手并且完成了。其实没有什么难的。但是因为我对Linux的了解非常局限,还是花了一番功夫,同时学了很多东西,在这里记一下。没有试图写一篇“手把手教你搬WP”,只是记录一些我觉得有帮助的东西,希望做同样的事情的且同样不是那么牛逼的Linux学习者们有用:)

虽说是WordPress搬家,但是任何一个小型网站搬家都差不多这样了吧,嘿嘿。

如果用cPanel和MySQLAdmin之类的东西可能就很傻瓜,但是第一cPanel太贵了(竟然要425多刀一年,我都笑了),第二VPS都买了必须必须要抓住每一个学Linux的机会啊。

过程如下(断断续续弄了好几天…):

环境

虚拟主机和VPS都是host2ez的,最牛逼的主机提供商。系统是CentOS Linux 5.6,apache(现在改名叫httpd)已经装好了,再装

yum php mysql mysql-server

就成。

文件

这个简单,cPanel把虚拟主机上文件打包,VPS上wget下来就好。WP的独立性做的好,文件路径改变不会有什么问题。备份用的插件BackUpWordpress倒因为出问题了,不能识别路径,我直接禁用掉了,VPS嘛马上弄个备份方案还不容易,不需要用WP的插件了。在[wordpress path]/wp_config.php里把信息改一下,数据库部分的怎么改见下面。

数据库

对数据库命令不了解的同学建议先看一下mysql的教程。我不能把所有操作都写出来…这次弄这个还学了不少数据库的东西…tutorial很容易搜到,我觉得有一个比较好的命令列表点 这里,里面包括了所有常用的命令。

在虚拟主机的cPanel – mysqladmin里备份出.sql文件,传上VPS,导入文件的命令是

mysql – u user_name -p database_name < file_name.sql

很多地方写的-p后面跟密码,我用的版本-p后面不跟东西,回车以后才提示输密码,可能是新版本不提倡显式输入密码了吧。非要用的话就–password=”xxxxxx”

如果你导出文件选的是整个mysql,需要打开文件把database”information_schema”部分删掉,否则会失败,这个db貌似是mysql自己的,不能改..不懂

之后要建立一个用户并给此用户分配使用相应db的权限,虽然我们也可以直接把root用户写进wp_config.php但是稍微有点安全意识的程序员都不会想要这么做的…虽然权限没什么大不了的,但是名字叫root就是不行! 所以进数据库:

mysql -u root -p

进去以后添加用户:

mysql> create user 'username'@'localhost' identified by 'mypass';

分配权限:

mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

然后就把这个用户甩给Wordpress啦(编辑wp_config.php)

测试的时候有一些问题

上面完了就能http进vps的ip看到博客了,但是不要去点任何东西…因为数据库里“本站”的地址还是原来的域名,这样如果你原来的网站还开着那么随便点个链接就进到原来网站了,如果没开那就can’t find page啦。

而且因为没法进后台改,所以只好进mysql改了

mysql> use viaxlcom_viaxlcom;
mysql> select * from wp_options where option_value rlike "^http";
+-----------+---------+-------------+----------------------------+----------+
| option_id | blog_id | option_name | option_value               | autoload |
+-----------+---------+-------------+----------------------------+----------+
|         2 |       0 | siteurl     | http://axlarts.com/blog      | yes      |
|        39 |       0 | home        | http://axlarts.com           | yes      |
|        41 |       0 | ping_sites  | http://rpc.pingomatic.com/ | yes      | 
+-----------+---------+-------------+----------------------------+----------+
3 rows in set (0.06 sec)
update wp_options set option_value="http://12.34.56.78/blog" where option_id=2;
update wp_options set option_value="http://12.34.56.78" where option_id=39;

这样就把VPS上的网站地址改成本身的IP了。

————————————-
另外我发现一些插件会出现权限问题,比如JW player(放flv视频用的插件),没法启用插件因为提示不能写目录,我整个www目录都是755权限,设置成777以后可以开启了,然后再弄回来。这个问题解决了但是原因一直不知道,直到我因为另一个问题搜了一下才搞明白。

另一个问题是:更新插件update的时候会提示我输入ftp帐号,以前没这事啊,于是我就去装了个vsftpd(ftp的服务端),设置好能更新了,但是为什么?后来搜到这篇文章 <Auto Update WordPress Without FTP> 解决了ftp的问题并且意识到上面的问题也和这个有关系,即因为目录的owner不是httpd,所以网站脚本没有对文件操作的权限。

/var/www目录的owner要设置成httpd的运行者(可以用ps aux或者top命令查看),可能是www,apache或者nobody或者其他的。我的是apache,所以在chown apache:apache /var/www -R之后update就不用输ftp了,我立刻关了vsftpd依然ok,可见之前是绕了弯子了,没权限还用ftp操作文件…

绑域名

进godaddy面板直接改A地址就好了,没有别的要操作的。

但是因为我本来虚拟主机上就放了两个网站,所以怎么在一个VPS上绑定多个域名多个网站?之前用cPanel是傻瓜操作,没有怎么弄?这个我也弄了好半天最终解决了,马上再写一篇单独说吧

好啦好啦,到此结束,路人有问题可以在下面留言~

24,827 thoughts on “网站/WordPress从虚拟主机搬家到VPS上

  1. melbet_vwet

    Давно искал инфу и наконец-то разобрался с этой проблемой. Авторы реально шарят в вопросе, никаких банальных советов из интернета. Рекомендую заглянуть, чтобы не совершать глупых ошибок, как я в прошлый раз. Вот melbet melbet — советую изучить на досуге. Мне лично это сэкономило кучу времени и нервов, так что делюсь от души.

    Reply
  2. 1xbet giris_saPt

    Arkadaslar uzun suredir ar?yordum. Girdim c?kt?m derken zaman kaybettim. En sonunda dogru adrese ulast?m.

    Bu isin puf noktalar? var. Su an en h?zl? cal?san 1xbet giris adresi tam olarak soyle: 1xbet güncel giriş 1xbet güncel giriş. Yani k?sacas? — 1xbet spor bahislerinin adresi degisti.

    Sorunsuz baglant? icin bu link yeterli. Kendi deneyimim buysa da — arayuz zaten al?s?k oldugunuz gibi. Gonul rahatl?g?yla girebilirsiniz…

    Reply
  3. syvenirnaya prodykciya s logotipom_obSl

    Народ, привет! Ох, уже голова болит с этим тимбилдингом, нужны нормальные презенты для партнеров. Ищу нормальное изготовление корпоративных сувениров с доставкой по Москве. бизнес подарки купить бизнес подарки купить Посоветуйте нормального поставщика сувенирной продукции с логотипом, чтобы не обдиралово было. Просили ещё брендированные кружки и толстовки. Заранее респект тем, кто откликнется с контактами проверенными.

    Reply
  4. Shawnhar

    Liked the balance between depth and brevity, never too shallow and never too long, and a stop at buildforwardthinkingmomentum kept the same balance going across the rest of the site, this is one of the harder skills in writing and the team here clearly has it figured out very well indeed across every page.

    Reply
  5. ZacharyWaync

    Good clean post, no errors and no awkward phrasing that breaks the reading flow, and a stop at learnandscaleprogress kept the same standard, definitely the kind of editorial care that earns a return visit because it tells me the writer is paying attention to details that matter to readers rather than just rushing publication.

    Reply
  6. Kak naiti cheloveka po nomery telefona_xsoa

    Случайно наткнулся на один гайд, Прям беда реальная: постоянно звонят с незнакомого телефона, а кто — вообще непонятно. Решил докопаться до истины и разобраться,. И знаете что? Тут главное знать, куда именно смотреть и какие базы юзать.

    Короче, если вас сейчас волнует тот же самый вопрос — пробить странный входящий звонок, то есть один проверенный временем вариант. Конкретно про то, как узнать по мобильному кто именно звонил — вот здесь всё максимально норм расписано: узнать адрес по номеру телефона бесплатно узнать адрес по номеру телефона бесплатно.

    Проверил лично на себе — тема реально работает. Потому что а тут выложена конкретная и структурированная информация. В общем, обязательно сохраните себе на будущее. Тема вроде избитая, но толковое решение всё же нашлось.

    Reply
  7. Wyattmus

    Bookmarking this for later, the kind of resource I want to keep nearby, and a quick look at findmomentumnext confirmed the rest of the site is worth the same treatment, definitely going into my reference folder for the next time the topic comes up at work or in conversation with someone who asks.

    Reply
  8. shkola onlain_cuoi

    Честно говоря, долго выбирал, варианты для учёбы, но после советов хороших знакомых наткнулся на один действительно толковый вариант. Если кратко, вот что я понял: современная онлайн-школа для детей — это серьёзный и комплексный подход. Там и программа насыщенная, без лишней воды, и дети занимаются с реальным интересом.

    В общем, кому реально нужно нормальное обучение в теме онлайн образование школа — почитайте подробности, вот здесь все расписано в деталях: интернет-школа интернет-школа.

    Если честно, даже не ожидал такого крутого качества. Потому что обычная школа часто проигрывает по всем фронтам, а тут организована именно живое регулярное общение с кураторами. Советую не тянуть и сразу изучить тему.

    Reply
  9. Danielles

    Now considering writing a longer note about the post somewhere, and a look at buildfocusedmomentum added more material for that note, content that prompts me to write rather than just consume is content with generative energy and this site is producing that generative effect for me at a higher rate than most sources.

    Reply
  10. tkan dlya mebeli_hikn

    Ребята, выручайте! Решил обновить кухонный уголок, а старую обивку уже не найти. Теперь мучаюсь — какую взять ткань для мебели, чтобы и выглядело достойно, и кошачьи когти выдержало. мебельные ткани цена https://tkan-dlya-mebeli-1.ru А то везде пишут разное, а на деле хочется купить ткань мебельную и забыть на пару лет. Нужен метров 15-20, может, кто знает нормального поставщика.

    Reply
  11. YaleFlure

    Took the time to read every paragraph rather than skimming for the punchline, and a quick visit to buildforwardclarity earned the same careful attention from me, that is the highest signal I can give about content quality because my default mode is rapid scanning rather than deliberate reading on most pages.

    Reply
  12. skolko stoit yzakonit pereplanirovky_roKn

    Ребята, привет! Долго думал, стоит ли начинать эту волокиту. Поменяли газовую плиту, сдвинули раковину, а стены вообще вынесли — думал, пронесёт. В общем, инспекция пришла и выписала предписание. И тут встал вопрос: согласование перепланировки квартиры цена согласование перепланировки квартиры цена ищу актуальные расценки: согласование перепланировки цена как у частников, так и через МФЦ. Или взносы в жилинспекцию за выдачу акта. А то риелторы называют цифры от балды. Без этого а если решите ипотеку рефинансировать, БТИ зарубит. Короче, просто сколько отдать, чтобы спать спокойно с новой планировкой.

    Reply
  13. Juddgor

    If quality blog writing is dying as people sometimes claim then this site is one piece of evidence that it has not died yet, and a look at explorefutureopportunitypaths extended that evidence, the broader cultural question about online writing has empirical answers in specific sites and this one is contributing to a more optimistic answer overall.

    Reply
  14. Leroyawalt

    Honest take is that this was better than I expected when I clicked through, and a look at focuscreatesprogress reinforced that, the bar for online content has dropped so much that finding something thoughtful and well constructed feels almost noteworthy now which says more about the average than about this site itself.

    Reply
  15. Nevilleeming

    Skipped to a specific section because I knew that was the question I had, and the answer was clean, and a stop at findgrowthdirections similarly delivered targeted answers without burying them, content engineered for readers who arrive with specific needs rather than open ended browsing is increasingly valuable in a search heavy reading environment.

    Reply
  16. Bennieniz

    Reading this felt productive in a way most internet reading does not, and a look at zingtorch continued that productive feeling, sometimes the open web feels like a waste of time but sites like this remind me why I still bother to look around rather than retreating to old reliable sources for everything I need.

    Reply
  17. BradJoigh

    A clear cut above the usual noise on the subject, and a look at draftport only made that gap wider in my view, the kind of place that earns its visitors through quality rather than through aggressive marketing or sponsored placements which is increasingly the only way most sites stay afloat across the modern web.

    Reply
  18. NathanappeF

    Now adjusting my mental model of how the topic fits into the broader landscape, and a look at graingrove extended that adjustment, content that affects my structural understanding rather than just my factual knowledge is content with deeper impact and this site is providing those structural updates at a meaningful rate consistently across topics.

    Reply
  19. JavonRearp

    Now appreciating that I did not feel exhausted after reading, and a stop at brightbanyan extended that energising quality, content that leaves me with more attention than it consumed is rare and the gap between draining and energising content is real over the course of a typical day spent reading widely online.

    Reply
  20. Axelassog

    Probably the kind of site that should be more widely read than it appears to be, and a look at createforwardthinking reinforced that quiet wish, the gap between a sites quality and its apparent reach is sometimes large and that gap exists for this site in a way that makes me want to mention it more.

    Reply
  21. YorkRig

    During the time spent here I noticed the absence of the usual distractions, and a stop at lobbydawn extended that distraction free experience, content that does not fight my attention with pop ups and modals and aggressive prompts is content that respects me and this site has clearly chosen the respectful approach throughout.

    Reply
  22. ErnestoMak

    Refreshing to find writing that does not try to manipulate the reader into clicking onto the next page through cliffhangers and forced engagement, and a stop at portguild continued in the same respectful way, this is what reader first design actually looks like in practice rather than just in marketing copy that sounds nice.

    Reply
  23. PierreDok

    Thanks for a post that does not try to be funny when it is not the moment for it, and a stop at createforwardexecutionsteps maintained the same appropriate seriousness, knowing when humour helps and when it just signals desperation for engagement is a sign of editorial maturity that many blogs have not developed yet.

    Reply
  24. ChaseJaith

    Really grateful for content like this, it does not waste my time and it does not insult my intelligence either, and a quick look at opaldunes was the same, balanced respectful writing that makes a person feel welcome rather than rushed through pages of forced engagement just to keep clicking around.

    Reply
  25. KimZem

    Worth marking this site as one to come back to deliberately rather than by accident, and a stop at createwithintention reinforced that intention, the difference between sites I find again by chance and sites I return to on purpose is meaningful and this one has clearly moved into the deliberate return category for me.

    Reply
  26. syvenirnaya prodykciya s logotipom_heSl

    Народ, привет! Такая ситуация — на планерке сказали срочно найти подарки для клиентов. Ищу нормальное изготовление корпоративных сувениров с доставкой по Москве. товары с логотипом https://suvenirnaya-produkcziya-s-logotipom-10.ru Посоветуйте нормального поставщика сувенирной продукции с логотипом, чтобы не обдиралово было. Нужно штук 300-500, но если будет норм цена, можем и больше взять. Заранее респект тем, кто откликнется с контактами проверенными.

    Reply
  27. OmarGip

    Following the post through to the end without my attention drifting once, and a look at palmmills earned the same uninterrupted attention, content that holds attention without manipulating it is content with substantive pull and this site has demonstrated that substantive pull across multiple pieces in a single reading session reliably here today.

    Reply
  28. MikeFes

    Thanks for taking the time to write this, it is clear that some thought went into how each point would land, and after I went through findyourwinningdirection I had a better grip on the topic, real value without the usual marketing noise people have to put up with online when searching for answers.

    Reply
  29. syvenirnaya prodykciya s logotipom_lwSl

    Народ, привет! Такая ситуация — на планерке сказали срочно найти подарки для клиентов. Ищу нормальное изготовление корпоративных сувениров с доставкой по Москве. продукция с логотипом на заказ https://suvenirnaya-produkcziya-s-logotipom-10.ru Говорят, сейчас модно заказывать корпоративные подарки сувениры из экокожи — но кто делает качественно. Просили ещё брендированные кружки и толстовки. Заранее респект тем, кто откликнется с контактами проверенными.

    Reply
  30. LloydBak

    A nicely understated post that does not shout for attention, and a look at curiopacts maintained the same quiet quality, understatement is a stylistic choice that distinguishes serious writing from attention seeking writing and this site has clearly committed to the understated approach as a core editorial value rather than just a phase.

    Reply
  31. Bradfordpab

    High quality writing, no marketing speak and no buzzwords that mean nothing, and a stop at micapacts kept that going, simple direct content that actually communicates something is harder to find than it should be and this is one of the rare places that gets it right consistently across many different posts.

    Reply
  32. Walterfut

    Скачать музыку бесплатно https://savesong.me и слушать любимые треки онлайн в хорошем качестве. Большая коллекция песен разных жанров, удобный поиск по исполнителям и альбомам, популярные новинки и хиты для прослушивания в любое время.

    Reply
  33. 1xbet giris_mfMr

    Uzun zamandır takipteyim. Sürekli engellenen sitelerden bıktım. En sonunda sağlam bir link buldum.

    Bahisle ilgilenen arkadaşlara duyurulur. Uyarıları dikkate alarak sistemi kurun. Giriş adresi aynen şu şekilde: 1xbet güncel giriş 1xbet güncel giriş. Özetle — 1xbet türkiye için tek doğru adres bu.

    Bonusları gayet iyi. Dost meclisinde öğrendim — başka yerde aramaya gerek yok. Selametle…

    Reply
  34. shkola onlain_aioi

    Честно говоря, долго выбирал, направления для детей, но после советов хороших знакомых наткнулся на один действительно толковый вариант. К слову, вот что я понял: современная школа онлайн — это не просто унылые вебинарчики. Там и преподаватели живые и вовлеченные, и дети занимаются с реальным интересом.

    В общем, кому надоело искать среди кучи мусора в теме онлайн образование школа — почитайте подробности, вот здесь все разжевано до мелочей: лбс это лбс это.

    Думаю, это как раз то, что сейчас нужно многим родителям. Потому что обычная школа часто проигрывает по всем фронтам, а тут организована именно живое регулярное общение с кураторами. Держите этот вариант у себя в закладках.

    Reply
  35. skolko stoit yzakonit pereplanirovky_riKn

    Ребята, привет! Я вообще в шоке, если честно. Поменяли газовую плиту, сдвинули раковину, а стены вообще вынесли — думал, пронесёт. В общем, теперь легализовывать этот бардак придётся официально. И тут встал вопрос: перепланировка квартиры цена перепланировка квартиры цена Кто сталкивался недавно — сколько стоит узаконить перепланировку в многоэтажке. Плюс эти дурацкие техусловия на вентиляцию. А то риелторы называют цифры от балды. Без этого всё равно потом квартиру не продать. Короче, просто сколько отдать, чтобы спать спокойно с новой планировкой.

    Reply
  36. skolko stoit yzakonit pereplanirovky_jlKn

    Ребята, привет! Соседи залили, решил сделать ремонт, а там. Акт скрытых работ потерял, да и проект сам переделывал. В общем, инспекция пришла и выписала предписание. И тут встал вопрос: сколько стоит перепланировка сколько стоит перепланировка говорят, согласование перепланировки квартиры цена сильно выросла после ужесточения норм. Или взносы в жилинспекцию за выдачу акта. А то риелторы называют цифры от балды. Без этого а если решите ипотеку рефинансировать, БТИ зарубит. Короче, нужна стоимость согласования перепланировки, реальная по рынку.

    Reply
  37. Kak naiti cheloveka po nomery telefona_icoa

    Уже отчаялся был найти хоть что-то стоящее. Ситуация дурацкая, потерял контакт со старым хорошим другом. Решил докопаться до истины и разобраться,. И знаете что? Тут главное знать, куда именно смотреть и какие базы юзать.

    Короче, если вас сейчас волнует тот же самый вопрос — пробить странный входящий звонок, то есть один реально работающий и живой сервис. Конкретно про то, где найти по телефонному номеру актуальные данные — вот здесь всё максимально норм расписано: посмотреть по номеру телефона где находится человек посмотреть по номеру телефона где находится человек.

    Друзьям ссылку скинул в телегу, им тоже помогло. Потому что а тут выложена конкретная и структурированная информация. В общем, кому надо — тот точно воспользуется. Век живи — век учись, как говорится.

    Reply
  38. Jacesherm

    Skipped the related products section because there was none, and a stop at ideaswithtraction also lacked any aggressive monetisation, content that is not constantly trying to convert me into a customer or subscriber is content that has confidence in its own value and that confidence shows up as a different reading experience.

    Reply
  39. vivod iz zapoya v stacionare_xjsr

    Всем доброго времени суток. Дело деликатное, но решил черкануть пару строк, потому что в экстренной ситуации трудно сориентироваться. Если срочно требуется квалифицированная медицинская помощь, лучше сразу обращаться к сертифицированным медикам.

    Знакомые вызывали бригаду в похожей ситуации чтобы помощь оказали без лишних хлопот и в спокойной атмосфере. Чтобы узнать точные цены и вызвать специалиста, можете ознакомиться по ссылке: выход из запоя стационар выход из запоя стационар.

    На этом ресурсе действительно дана полная информация, так что найдете ответы на свои вопросы. Надеюсь, эта рекомендация поможет вовремя принять правильные меры. Пусть все будет хорошо!

    Reply
  40. melbet_kzet

    Ребят, наконец-то наткнулся на реальный опыт. Там всё разложено по полочкам, без лишней воды и тупых SEO-текстов. Сам долго мучился, пока не нашел этот гайд. Вот мелбет скачать на андроид мелбет скачать на андроид — переходите, там вся суть. Там внутри и примеры, и пошаговые инструкции, короче полный фарш.

    Reply
  41. syvenirnaya prodykciya s logotipom_rymr

    Коллеги, всем привет! Срочно нужна консультация тех, кто уже заказывал мерч для бизнеса. Посоветуйте нормальное изготовление корпоративных сувениров — чтобы и кружки не облазили, и ручки писали. бизнес подарок бизнес подарок Где сейчас лучше заказывать корпоративные подарки сувениры — в России или все-таки из Китая везти. Бюджет пока не утвержден, поэтому хочу понять рыночные цены. Киньте ссылки или названия компаний, буду очень благодарен.

    Reply
  42. Leroyawalt

    Really like that there are no exclamation marks or all caps shouting throughout the post, and a quick visit to focuscreatesprogress maintained the same calm voice, restraint in punctuation signals confidence in the content and this site clearly trusts its substance to do the persuading rather than relying on typographic emphasis.

    Reply
  43. JavonRearp

    A small thank you note from me to the team behind this work, the post earned it, and a stop at brightbanyan suggested more thanks would be in order over time, recognising the people who do good writing online is something I try to remember to do because the alternative is silence and silence rewards mediocrity unfortunately.

    Reply
  44. shkola onlain_mdSt

    Давно присматривался к разным предложениям, где реально не грузят лишней теорией. Особенно когда речь про образовательные онлайн школы — тут ведь важен подход. У меня дочка как раз перешел на удаленку, так что пришлось перебрать кучу вариантов. В общем, можете глянуть сами: школа дистанционного обучения школа дистанционного обучения Я если кому интересно ещё раньше вообще думал, что это всё несерьёзно. Оказалось — зря сомневался. У них и программа грамотная. Сам теперь советую знакомым. Надеюсь, поможет в выборе.

    Reply
  45. NathanappeF

    Now adjusting my mental model of how the topic fits into the broader landscape, and a look at graingrove extended that adjustment, content that affects my structural understanding rather than just my factual knowledge is content with deeper impact and this site is providing those structural updates at a meaningful rate consistently across topics.

    Reply
  46. OmarGip

    Ended up here on a wandering afternoon and was glad I stayed for the read, and a stop at palmmills extended the wandering into a proper exploration of the site, the kind of place that rewards aimless clicking with something genuinely interesting rather than the shallow content that mostly populates the modern open web.

    Reply
  47. ChaseJaith

    Came here from another site and ended up exploring much further than I planned, and a look at opaldunes only encouraged more exploration, the kind of place where one click leads to another not through manipulative design but through genuinely interesting content is rare and worth highlighting when found like this somewhere on the open internet.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *